Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to append images to array from directory?

I use this code to append images in array from directory

for myIndex in 1...17 {
                
    let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
    let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
    let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
    let dirPath = paths.first
    let imageURL = URL(fileURLWithPath: dirPath!).appendingPathComponent("\(index)/\(myIndex).jpg")
    let image = UIImage(contentsOfFile: imageURL.path)
    imageArray.append(image!)
                
}

but I have this error:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an
Optional value

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

in this line:

imageArray.append(image!)

How to fix it?

>Solution :

It’s pretty clear. You’re forcing unwrap image with ! in the case of nil. So, I think you should:

  1. Unwrap the image in a safe way such as if let or guard let:
if let image = UIImage(contentsOfFile: imageURL.path) {
    imageArray.append(image) //without "!"
}
  1. Double check why the image’s path is nil.

You can take a look at the app’s container. If you saved the image successfully, it should be there.

Xcode -> Window -> Devices and Simulators

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading