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