0
我要将图像保存到iphone设备并从中读取。 所以我写了这样的函数。如何将图像保存到iPhone设备存储器或从中读取图像?
/*
* save image to local device
*/
func saveImageToLocal(image: UIImage, fileName: String) {
if let data = UIImagePNGRepresentation(image) {
let filePath = self.getDocumentsDirectory().appendingPathComponent(fileName)
try? data.write(to: filePath, options: .atomic)
}
}
/*
* get image from local device
*/
func getImageFromLocal(fileName:String) -> UIImage? {
if let filePath = "\(self.getDocumentsDirectory())\(fileName)" as String! {
if let image = UIImage(contentsOfFile: filePath) {
return image
}
}
return nil
}
/*
* get document directory to save/read local file
*/
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
但它没有正常工作。 我有这个错误吗? 我该如何执行此操作? 此致敬礼。
为什么'filePath'在保存和获取方法中创建方式如此不同?更新get方法以像在保存方法中那样创建它。 – rmaddy
谢谢!你的帮助非常好。 – LoveCode