swift - 如何从 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
}
解决方案
你可以像这样检索它
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)
}
}
}
推荐阅读
- java - Tomcat 服务器 - 启动时出错
- python - Perl 中的 =~ 是否等同于 Python 中的 re.match?
- cmake - cmake 生成的附加 CGAL 目标的目的是什么
- java - Java SSL OCSP 检查无法验证整个信任链,证书未指定 OCSP 响应者
- javascript - 使用 CSS/JS 渐变淡出 div
- javascript - 我想在悬停时更改 html 类
- r - 如何在改变一秒时重置一个sliderInput而不触发Shiny中的反应
- css - 如何对齐图标和文本
- python - 一些数学,以及定义语句中的更多函数
- xml - 使用 XSLT 1.0 与嵌套/分层结构有间隙的扁平结构