我想使用 userdefaults 保存图像并在另一个 View 中使用此代码使用它,但它显示错误。
UserDefaults.standard.set(img , forKey : "simg")
请帮帮我
最佳答案
这就是我要做的。您可以将其保存到多个位置,用户的文档文件夹通常是最好的:
func cacheImageAsPNG(image: UIImage, localID: String) {
let userDocumentsURL = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
if let imageData = UIImagePNGRepresentation(image) {
let filename = userDocumentsURL.appendingPathComponent("\(localID).png")
if FileManager.default.createFile(atPath: filename.path, contents: imageData, attributes: nil) {
print("wrote file:\n\(filename.path)")
} else {
print("couldn't write the file:\n\(filename.path)")
}
}
}
如果您希望系统在内存使用高峰时将其删除,则缓存目录是更好的位置:
let cachesPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last!
编辑:检索图像
func cachedImage(localID: String) -> UIImage? {
let userDocumentsURL = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
let cachePath = userDocumentsURL.appendingPathComponent("\(localID).png")
return UIImage(named: cachePath.path)
}
关于ios - 如何保存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44977831/