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
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:
- Unwrap the image in a safe way such as
if letorguard let:
if let image = UIImage(contentsOfFile: imageURL.path) {
imageArray.append(image) //without "!"
}
- 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
