从URL保存图像并使其保持IOS Swift

时间:2016-12-30 08:05:36

标签: ios swift uiimage data-persistence

我想保存网址中的图片,然后在我的应用中使用它们。

我将它们保存在变量中但是如何在用户删除应用程序之前保持这些变量?

以下是在变量中保存图像的代码

    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   
            }
        }
    }

如何保存背景图像以保持?

谢谢!

2 个答案:

答案 0 :(得分:1)

对于Swift 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)
    }
}

调用getDocumentsDirectory()

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

答案 1 :(得分:0)

我建议您将图像存储在文档目录中,下载代码后可以使用以下代码,并从NSData转换为UIImage

Swift 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")
}