Reputation: 649
I want to save image using userdefaults, what I want to achieve is after image being change and the app terminate it. the image user change is still there. how do I achieve this with userdefaults.
This is my code when user pick image and save it in userdefaults
var data: Data? //I make a reference data to save imageData in pickerController
@objc func handleImagePicker() {
let imagePickerController = UIImagePickerController()
imagePickerController.allowsEditing = true
imagePickerController.sourceType = .photoLibrary
imagePickerController.delegate = self
present(imagePickerController, animated: true)
}
@objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let editedImage = info[.editedImage] as? UIImage {
guard let imageData = editedImage.jpegData(compressionQuality: 0.5) else { return }
self.data = NSKeyedArchiver.archivedData(withRootObject: imageData)
UserDefaults.standard.set(data, forKey: "profileImageEditedKey")
UserDefaults.standard.synchronize()
profileImageView.image = editedImage.withRenderingMode(.alwaysOriginal)
} else if let originalImage = info[.originalImage] as? UIImage {
guard let imageData = originalImage.jpegData(compressionQuality: 1) else { return }
self.data = NSKeyedArchiver.archivedData(withRootObject: imageData)
UserDefaults.standard.set(data, forKey: "profileImageOriginalKey")
UserDefaults.standard.synchronize()
profileImageView.image = originalImage.withRenderingMode(.alwaysOriginal)
}
dismiss(animated: true)
}
This is the code I place in viewWillAppear when I fetch the data after the app terminate
private func fetchData() {
guard let data = data else { return }
guard let image = NSKeyedUnarchiver.unarchiveObject(with: data) as? UIImage else { return }
profileImageView.image = image.withRenderingMode(.alwaysOriginal)
print("fetch...")
}
Upvotes: 0
Views: 80
Reputation: 471
it is not a good idea to save big data in userdefaults
, it is often not recommended as it is not the most efficient way to save images; a more efficient way is to save your image in the application's Documents Directory. you use Data
write
func to do that.
there are other third library too.
if you insist using UserDefaults
to save image
guard let imageData = editedImage.jpegData(compressionQuality: 0.5) else { return }
UserDefaults.standard.set(imageData, forKey: "profileImageEditedKey")
UserDefaults.standard.synchronize()
to get image from UserDefaults
guard let data = UserDefaults.standard.object(forKey: "profileImageOriginalKey") as? Data else {
return;
}
let image = UIImage.init(data: data);
Upvotes: 1