ios - 如何保存图像

标签 ios swift3

我想使用 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/

相关文章:

ios - 如何将 NSString 转换为 UTF-8 以外的编码?

swift - 访问扩展中的结构时的保护级别问题

ios - Struct Gobal 在不应该的时候从另一个 VC 更新

ios - 由于未捕获的异常 'NSInternalInconsistencyException' 终止应用程序,- Swift 3

ios - 将主机名字符串解析为 IP 字符串

iphone - Cocos2d 调试器控制台显示了很多东西

objective-c - 关闭商店 View 后在 App Purchase 中崩溃

ios - 核心动画围绕点旋转

ios - swift 3 游戏中心 : number of participants are always 4

ios - 如何在 SpriteKit 场景编辑器中访问 Navigation Graph 的对象