Khoury Khoury - 1 year ago 63
Swift Question

Why do my images saved in directory not appear after a new build is installed?

I save images from user's photo library like this

func saveImage (image: UIImage, path: String ) -> Bool{
let jpgImageData = UIImageJPEGRepresentation(image, 1.0)
let result = jpgImageData!.writeToFile(path, atomically: true)
return result

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!

let imagePath = fileInDocumentsDirectory(myImageName)
saveImage(yourPickedImage, path: imagePath)

And I read those images like this

func loadImageFromPath(path: String) -> UIImage? {
let image = UIImage(contentsOfFile: path)
return image

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! Cell

cell.backgroundImage.image = loadImageFromPath(String(Globals.imagesArray[(indexPath as NSIndexPath).item]))

This all works fine, until I install a new build in Xcode 8, the images do not load into the UIImageView.

I have a feeling it could be that the file path changes, because the images do load if I quit and restart the app, but not from a new build.

How do I remedy this?


Answer Source

The problem, as you already suspect, is that you are saving the value of path and using it later to try to load the file. You can't do that, because the path will be different each time. You need to go through all the work of calling imagePath = fileInDocumentsDirectory(myImageName) in order to load the path, just as you did when you saved it.

(Also, though this has nothing to do with your question, constructing a URL and then making a string path out of it, as you do in fileInDocumentsDirectory, is silly. Stick to the URL throughout!)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download