Saved file disappears after recompiling application

I am writing an iOS application (in Swift) that includes options for saving images to a safe place. As soon as an image is selected (from the camera or saved images), it is written to a file and the file location is saved to NSUserDefaults. I can re-access the image when I restarted the application after killing it. But when I run the application again from Xcode (after recompiling), the image will be lost from the image path.

Joining save and load 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 the reason for this?

+4
source share
2 answers

.

NSUserDefaults ( getDocumentsURL() NSURL).

, , , , - , .

:

 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

}
+4

. , .

0

Source: https://habr.com/ru/post/1654436/


All Articles