首页 > 解决方案 > 如何从 Swift 中的文档文件夹中检索保存的 UIImageViews?

问题描述

我正在创建这个应用程序,它可以拍照并将其显示在 UIImageView 中。当我按下保存按钮时,它应该将图像保存到文档目录。然后我希望能够在我的收藏视图中检索这些图像。我有下面的代码保存图像,但我将如何在我的收藏视图中检索它?谢谢!

第一个视图控制器 - 保存图像

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!)
      }

}

第二个视图控制器 - 检索图像

    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
}

标签: swiftuicollectionviewuiimageview

解决方案


你可以像这样检索它

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
}

为了节省

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)
        }
    }
}

推荐阅读