How to save image

2020-05-06 11:03发布

I want to save image with userdefaults and use it in another view with this code but it shows an error .

UserDefaults.standard.set(img , forKey : "simg")

please help me

标签: ios swift3
3条回答
在下西门庆
2楼-- · 2020-05-06 11:49

This is how I would do it. You have multiple places to save it to, the user's Documents folder is usually best:

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

if you want it erased by the system during times of peak memory usage, the cache directory is a better place:

 let cachesPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last!

Edit: Retrieving the Image

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)
}
查看更多
SAY GOODBYE
3楼-- · 2020-05-06 12:01

As others have said, don't save images to user defaults. It's only intended for small bits of data.

If all you want to do is to pass an image in another view controller, and you don't care about making the image persist if the user quits and re-launches the app, just pass the image in prepareForSegue.

查看更多
唯我独甜
4楼-- · 2020-05-06 12:04

You can't save a UIImage directly to NSUserDefaults. You could save it as NSData, but it really is not advisable. NSUserDefaults is meant to store small bits of information in key value pairs. If you start throwing images in there, you could overload the space reserved for it. The contents of the NSUserDefaults is written to a plist. I believe any time you access the user defaults, it reads the whole file. If you put large images in there, it will cause a lot of unnecessary I/O.

If you still decide to do it (not recommended), here is a good post on getting an NSData object from the image.

查看更多
登录 后发表回答