Search code examples
swiftuicollectionviewuiimageview

How to retrieve saved UIImageViews from documents folder in Swift?


Im creating this app that takes a picture and displays it in a UIImageView. When I press on the save button it should save the images to the document directory. Then I want to be able to retrieve these images in my collection view. I have the code below that saves the images but how would I retrieve it in my collection view? Thanks!

First View Controller - save images

func saveImage(image: UIImage) -> String {

let imageData = NSData(data: image.pngData()!)
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory,  FileManager.SearchPathDomainMask.userDomainMask, true)
 let docs = paths[0] as NSString
 let uuid = NSUUID().uuidString + ".png"
 let fullPath = docs.appendingPathComponent(uuid)
 _ = imageData.write(toFile: fullPath, atomically: true)
return uuid
 }



@IBAction func didPressSaveButton(_ sender: Any) {
                      

 for _ in self.images {
   _ = self.saveImage(image: self.imageView.image!)
      }

}

Second View Controller- retrieve images

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 
}

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

    return cell
}

Solution

  • You can retrieve it like this

    func loadImageFromDocumentDirectory(nameOfImage : String) -> UIImage? {
    
        let documentDirectory = FileManager.SearchPathDirectory.documentDirectory
        let userDomainMask = FileManager.SearchPathDomainMask.userDomainMask
        let paths = NSSearchPathForDirectoriesInDomains(documentDirectory, userDomainMask, true)
        if let dirPath = paths.first{
            let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(nameOfImage)
            if let image = UIImage(contentsOfFile: imageURL.path) {
                return image
    
            } else {
                print("image not found")
    
                return nil
            }
        }
        return nil
    }
    

    And for saving

    func saveImageToDocumentDirectory(image: UIImage , imageName: String) {
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let fileName = imageName // name of the image to be saved
        let fileURL = documentsDirectory.appendingPathComponent(fileName)
        if let data = image.jpegData(compressionQuality: 1),
            !FileManager.default.fileExists(atPath: fileURL.path){
            do {
                try data.write(to: fileURL)
                print("file saved")
            } catch {
                print("error saving file:", error)
            }
        }
    }