Swift - 将图像保存和检索到 tmp 文件夹

Swift - Saving and retrieving images to the tmp-folder

我想保存并稍后检索我保存到我的 tmp 文件夹中的图像,这是我第一次使用文件系统,所以如果我没有希望,请多多包涵。

现在,我正在像这样保存正在检索的图像:

let userImageFile = object["Image"] as PFFile
userImageFile.getDataInBackgroundWithBlock { (imageData: NSData!, error: NSError!) -> Void in
    if error == nil {
        image = UIImage(data:imageData)
        let imageToSave:NSData = UIImagePNGRepresentation(image)

        let path = NSTemporaryDirectory() + "MyFile"
        imageToSave.writeToFile(path, atomically: true)
    }
}

假设这是保存它的正确方法我也想检索图像。如何创建对要检索的文件的引用。我以前只用过 userDefaults,然后你给你保存的文件加了一个名字,我不知道你在保存到 tmp 文件夹时会怎么做。

任何有关如何解决此问题的建议将不胜感激。

使用您已经创建的路径稍后检索图像,您可以将此路径保存在 userDefaults 中,或者保存在数组中,或者如果您不需要存储它,则可以保存在您喜欢的任何内容中。

let tempImage = UIImage(contentsOfFile: path)

但请确保您保存的图像带有后缀,例如 .png,以便该方法了解文件的图像类型。

记得检查该位置是否还有图像,因为不能保证图像仍然存在,因为它在 NSTemporaryDirectory() 中。我建议阅读 this article 关于临时目录的主题。