I want to put a UIImage
array into UserDefaults
and then retrieve it. After that set the retrieved images in an image view. How can I do that?
First of all that is not ideal way to save image in user default but if you want you can do following things
Save
let imageData = NSKeyedArchiver.archivedData(withRootObject: placesArray)
UserDefaults.standard.set(imageData, forKey: "images")
Retrieve
let imageData = UserDefaults.standard.object(forKey: "images") as? NSData
if let imageData = imageData {
let imageArray = NSKeyedUnarchiver.unarchiveObject(with: imageData as Data) as? [UIImage]!
print(placesArray)
}
Note: You should save your image in document directory and then save that name array to user default.
Save image in document directory
func saveImageDocumentDirectory(){
let fileManager = NSFileManager.defaultManager()
let paths = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString).stringByAppendingPathComponent("apple.jpg")
let image = UIImage(named: "apple.jpg")
print(paths)
let imageData = UIImageJPEGRepresentation(image!, 0.5)
fileManager.createFileAtPath(paths as String, contents: imageData, attributes: nil)
}
Retrieve image
func getImage(name : String){
let fileManager = NSFileManager.defaultManager()
let imagePAth = (self.getDirectoryPath() as NSString).stringByAppendingPathComponent(name)
if fileManager.fileExistsAtPath(imagePAth){
self.imageView.image = UIImage(contentsOfFile: imagePAth)
}else{
print("No Image")
}
}
func getDirectoryPath() -> String {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths[0]
return documentsDirectory
}