Search code examples
iosswiftnsfilemanagertmp

Swift - Saving and retrieving images to the tmp-folder


I want to save and then later retrieve the images I'm saving to my tmp folder, this is my first time using the file-system so please bear with me if I'm hopeless.

Right now, I'm saving the images that are being retrieved like this:

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

Assuming this is the correct way to save it I also want to retrieve the images. How do I create a reference to the file I want to retrieve. I've only used the userDefaults before, and there you add a name to the file you're saving, I can't see how you would do it when saving to the tmp-folder.

Any suggestions on how to solve this would be appreciated.


Solution

  • Use the path you've created already to retrieve the image later, you can save this path in the userDefaults for instance, or in an array or whatever you like if you don't need it to be stored.

    let tempImage = UIImage(contentsOfFile: path)
    

    Make sure you save the image with a suffix though, .png for instance, so the method understands that the what type of image the file is.

    Remember to check if there is still an image at the location, as there is no guarantee that the image is there still, since it's in the NSTemporaryDirectory(). I'd recommend reading this article on the subject of temporary directories.