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?