Is it possible to save images into NSUserDefaults as an object and then retrieve for further use?
Is it possible to save images into NSUserDefaults as an object and then retrieve for further use?
Since this question has a high google search index - here's @NikitaTook's answer in today's day and age i.e. Swift 3 and 4 (with exception handling).
Note: This class is solely written to read and write images of JPG format to the filesystem. The Userdefaults stuff should be handled outside of it.
writeFile takes in the file name of your jpg image (with .jpg extension) and the UIImage itself and returns true if it is able to save or else returns false if it is unable to write the image, at which point you can store the image in Userdefaults which would be your backup plan or simply retry one more time. The readFile function takes in the image file name and returns a UIImage, if the image name passed to this function is found then it returns that image else it just returns a default placeholder image from the app's asset folder (this way you can avoid nasty crashes or other weird behaviors).
import Foundation
import UIKit
class ReadWriteFileFS{
func writeFile(_ image: UIImage, _ imgName: String) -> Bool{
let imageData = UIImageJPEGRepresentation(image, 1)
let relativePath = imgName
let path = self.documentsPathForFileName(name: relativePath)
do {
try imageData?.write(to: path, options: .atomic)
} catch {
return false
}
return true
}
func readFile(_ name: String) -> UIImage{
let fullPath = self.documentsPathForFileName(name: name)
var image = UIImage()
if FileManager.default.fileExists(atPath: fullPath.path){
image = UIImage(contentsOfFile: fullPath.path)!
}else{
image = UIImage(named: "user")! //a default place holder image from apps asset folder
}
return image
}
}
extension ReadWriteFileFS{
func documentsPathForFileName(name: String) -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let path = paths[0]
let fullPath = path.appendingPathComponent(name)
return fullPath
}
}
Swift 4.x
Xcode 11.x
func saveImageInUserDefault(img:UIImage, key:String) {
UserDefaults.standard.set(img.pngData(), forKey: key)
}
func getImageFromUserDefault(key:String) -> UIImage? {
let imageData = UserDefaults.standard.object(forKey: key) as? Data
var image: UIImage? = nil
if let imageData = imageData {
image = UIImage(data: imageData)
}
return image
}