Search code examples
iosswiftnsfilemanager

ios FileManager losing stored data when rebuilding app


I'm trying to store images inside the app's document folder, so the user can retrieve them at any later time that they want to. This is my code to store them:

func store(_ image: UIImage) -> String {
    let imageName = "\(Date().timeIntervalSince1970)"
    let imagePath = "\(documentasPath)/\(imageName).png"

    let imageData = UIImagePNGRepresentation(image)

    fileManager.createFile(atPath: imagePath, contents: imageData, attributes: nil)

    return imagePath
}

And this is my code to retrieve the image from the storage:

func retrieveImage(from path: String) -> UIImage? {

    guard fileManager.fileExists(atPath: path) else {
        return nil
    }

    return UIImage(contentsOfFile: path)
}

It seems to work fine, except when I rebuild the app from xcode. Then all of my stored images disappear (although all of the paths I stored that pointed to them are still present and correct).

Is this some behavior of the default file manager? And is there a way to avoid this from happening? I want the images to only be deleted either manually or when I uninstall the app.

Thanks


Solution

  • The problem is that you are storing an absolute path. You can't do that, because your app is sandboxed, which means (in part) that the URL of the Documents folder can change. Store just the document name, and each time you want to save to it or write from it, calculate the path to the Documents folder again and append the document name and use that result as your path.