0

Goal is to get the image names from a directory and add them to an array of UIImages.

 var photoArray = [UIImage]()
 

 func getImageFromDocumentDirectory() -> [UIImage] {
    let fileManager = FileManager.default
    var imageNames = [String]()
    let imagePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, 
 .userDomainMask, true)[0] as NSString).appendingPathComponent("DIRECTORYNAME")
    do {
        let items = try fileManager.contentsOfDirectory(atPath: imagePath)
        for item in items {

This is where I'm getting the problem: error: Found nil ( let images )

 let images = UIImage(contentsOfFile: item)
 photoArray.append(images!)
        }
    } catch {
        print(error.localizedDescription)
    }
    return photoArray
}

Adding the func to a collection View to pull images.

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) 
 -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CELL", 
 for: indexPath) as! CELL

 let images = getImageFromDocumentDirectory()
 // photoImageView is a UIImageView in the cell.
 cell.photoImageView.image = images[indexPath.row]
 }

1 Answer 1

1

The problem is that – as you mentioned correctly – contentsOfDirectory(atPath returns an array of image names. To read the images from disk you need the full path.

I recommend to use the URL related API

func getImageFromDocumentDirectory() -> [UIImage] {
    var images = [UIImage]()
    let fileManager = FileManager.default
    do {
        let documentsDirectoryURL = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
        let folderURL = documentsDirectoryURL.appendingPathComponent("DIRECTORYNAME")
        let urls = try fileManager.contentsOfDirectory(at: folderURL, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
        for url in urls {
            if let data = try? Data(contentsOf: url),
               let image = UIImage(data: data) {
                 images.append(image)
            }
        }
    } catch {
        print(error.localizedDescription)
    }
    return images
}
Sign up to request clarification or add additional context in comments.

3 Comments

This would unnecessarily load all files located in Documents directory to memory even if they are not images. I would at least check the URL type identifier to filter the desired types. A file larger than the available memory would probably freeze/crash the app.
maybe something like if let typeIdentifier = (try? url.resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier, ["public.image","public.png","public.jpeg"].contains(typeIdentifier), or at least check the URL pathExtension
This in in a sub directory of "documents" where only images are going. I find it's better to create individual folders for specific filetypes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.