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
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
This is how I would do it. You have multiple places to save it to, the user's Documents folder is usually best:
if you want it erased by the system during times of peak memory usage, the cache directory is a better place:
Edit: Retrieving the Image
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
.You can't save a UIImage directly to
NSUserDefaults
. You could save it asNSData
, 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 theNSUserDefaults
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.