2016-12-30 16 views
2

我想從一個URL保存圖像,然後使用他們我的應用程序中。保存圖像,並使其持續IOS斯威夫特

我救了他們的變量,但我怎麼可以讓他們繼續下去,直到用戶刪除應用程序?

下面是變量

let backgroundURL:NSURL? = NSURL(string: "http://i.imgur.com/4AiXzf8.jpg") 
    DispatchQueue.global(qos: .userInitiated).async { 
     let backgroundData:NSData? = NSData(contentsOf: backgroundURL as! URL) 
     DispatchQueue.main.async { 
      if (backgroundData != nil) { 
       background = UIImage(data: backgroundData! as Data 
      } 
     } 
    } 

我如何保存的背景圖像堅持保存圖像的代碼?

謝謝!

+0

來電getDocumentsDirectory你不應該在你的問題解決方案複製。你應該接受一個答案,或者如果你找到自己的答案,請爲你的問題添加一個答案。 – FredericP

+0

完成,謝謝 –

+0

不客氣! – FredericP

回答

-1

對於斯威夫特3

// Assuming background is UIImage 
if let image = background { 
    if let data = UIImagePNGRepresentation(image) { 
     let filename = getDocumentsDirectory().appendingPathComponent("copy.png") 
     try? data.write(to: filename) 
    } 
} 

即()

func getDocumentsDirectory() -> URL { 
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) 
    let documentsDirectory = paths[0] 
    return documentsDirectory 
} 
+0

感謝Museer安薩里語法! –

+0

@MikeMe歡迎bro :)快樂的編碼 –

0

我建議你存儲的圖像在你的文檔目錄下面的代碼,你將能夠使用你下載的圖像,並轉換爲的UIImage從NSData的

雨燕2.3

let documentsDirectoryURL = try! NSFileManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true) 
// Name of Image you want to store 
let fileURL = documentsDirectoryURL.URLByAppendingPathComponent("ImageName.jpg") 

if !NSFileManager.defaultManager().fileExistsAtPath(fileURL.path!) { 
    if UIImageJPEGRepresentation(image, 1.0)!.writeToFile(fileURL.path!, atomically: true) { 
     print("Image saved") 
    } else { 
     print("error saving Image") 
    } 
} else { 
    print("Image name already exists") 
} 

後這裏是你如何能得到圖像

let fileManager = NSFileManager.defaultManager() 
let imagePAth = (self.getDirectoryPath() as NSString).stringByAppendingPathComponent("imageName.jpg") 

if fileManager.fileExistsAtPath(imagePAth){ 
let myImage: UIImage = UIImage(contentsOfFile: imagePAth) 
} 
else{ 
print("No Such Image") 
} 
+0

我想在swift 3中'UIImageJPEGRepresentation'會變成swift的'Data',所以它應該是'write(to:fileURL,options:)'? – Tj3n

+0

是啊,我應該有答案何況這是爲SWIFT 2.3 –

+0

謝謝Dev_Tandel –