Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saved file is gone after recompiling the App

I am writing an iOS app(in Swift) that includes and options to save pictures to a safe location. Once a picture is chosen(from Camera or Saved Images), it is written to the File and the file location is saved in NSUserDefaults. I am able to re-access the image, when I relaunch the app after killing it. But when I run the app from Xcode again(after recompiling), the image is lost from the Image path.

Attaching the saving and loading functions below

 func getDocumentsURL() -> NSURL {

        let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]

        return documentsURL
    }

    func fileInDocumentsDirectory(filename: String) -> String {

        let fileURL = getDocumentsURL().URLByAppendingPathComponent(filename)
        return fileURL.path!

    }


    func saveImage (image: UIImage, path: String ) -> Bool{



//        let pngImageData = UIImagePNGRepresentation(image)

        let jpgImageData = UIImageJPEGRepresentation(image, 1.0)   // if you want to save as JPEG
        let result = jpgImageData!.writeToFile(path, atomically: true)

        return result

    }

    func loadImageFromPath(path: String) -> UIImage? {

        let image = UIImage(contentsOfFile: path)

        if image == nil {

            print("missing image at: \(path)")
        }
        print("Loading image from path: \(path)") // this is just for you to see the path in case you want to go to the directory, using Finder.
        return image

    }

What could be causing this?

like image 850
Sidharth J Dev Avatar asked Sep 13 '16 08:09

Sidharth J Dev


2 Answers

The Document Directory path is different after each run.

Save to NSUserDefaults only the relative path from the Documents Directory (what you append to the getDocumentsURL() NSURL).

So in your case, you don't specify a subdirectory in your apps Document Directory, so the only thing you need on the next run, is the file name that you saved.

After that, you can retrieve the saved image with:

 func loadImageNamed(name: String) -> UIImage? {

   let imagePath = fileInDocumentsDirectory(name)
   let image = UIImage(contentsOfFile: imagePath)

    if image == nil {

        print("missing image at: \(path)")
    }
    print("Loading image from path: \(path)") // this is just for you to see the path in case you want to go to the directory, using Finder.
    return image

}
like image 50
Dejan Skledar Avatar answered Sep 22 '22 01:09

Dejan Skledar


When reinstalling the app, the documents directory will change. You shouldn't save the full path, but a relative path from the documents directory.

like image 28
Jesús A. Álvarez Avatar answered Sep 21 '22 01:09

Jesús A. Álvarez