Save UIImage array in NSUserDefaults
You can easily save your image in documentDirectory as below:
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let fileURL = documentDirectory?.appendingPathComponent(yourImageName)
and then, you can give your image to UserDefaults
Save UIImage to UserDefault as Array , Swift
Something like this would work:
extension UserDefaults {
func imageArray(forKey key: String) -> [UIImage]? {
guard let array = self.array(forKey: key) as? [Data] else {
return nil
}
return array.flatMap() { UIImage(data: $0) }
}
func set(_ imageArray: [UIImage], forKey key: String) {
self.set(imageArray.flatMap({ UIImagePNGRepresentation($0) }), forKey: key)
}
}
Usage:
let imageArray = [image1, image2, image3]
UserDefaults.standard.set(imageArray, forKey: "images")
let images = UserDefaults.standard.imageArray(forKey: "image")
However, I wouldn't recommend storing an array of images in UserDefaults
. Storing the images as files would probably be more appropriate. You could then store their paths in UserDefaults
.
saving and reading array of images with its data in NSUserDefaults or in Document Directory
You can't add images to user defaults, they aren't supported. You'll need to convert the image to data and save that instead (either to user defaults or, better, onto disk in a file...
imageArray.insert(UIImageJPEGRepresentation(img, 0.75), atIndex: self.imgIndex)
Error when trying to save image in NSUserDefaults using Swift
NSUserDefaults
isn't just a big truck you can throw anything you want onto. It's a series of tubes which only specific types.
What you can save to NSUserDefaults
:
NSData
NSString
NSNumber
NSDate
NSArray
NSDictionary
If you're trying to save anything else to NSUserDefaults
, you typically need to archive it to an NSData
object and store it (keeping in mind you'll have to unarchive it later when you need it back).
There are two ways to turn a UIImage
object into data. There are functions for creating a PNG representation of the image or a JPEG representation of the image.
For the PNG:
let imageData = UIImagePNGRepresentation(yourImage)
For the JPEG:
let imageData = UIImageJPEGRepresentation(yourImage, 1.0)
where the second argument is a CGFloat
representing the compression quality, with 0.0
being the lowest quality and 1.0
being the highest quality. Keep in mind that if you use JPEG, each time you compress and uncompress, if you're using anything but 1.0
, you're going to degrade the quality over time. PNG is lossless so you won't degrade the image.
To get the image back out of the data object, there's an init
method for UIImage
to do this:
let yourImage = UIImage(data:imageData)
This method will work no matter how you converted the UIImage
object to data.
In newer versions of Swift, the functions have been renamed, and reorganized, and are now invoked as:
For the PNG:
let imageData = yourImage.pngData()
For the JPEG:
let imageData = yourImage.jpegData(compressionQuality: 1.0)
Although Xcode will autocorrect the old versions for you
Saving NSMutableArray with UIImages to NSUserDefaults
Yes, you'll need to either use the UIImagePNGRepresentation
or UIImageJPEGRepresentation
functions to retrieve the image's binary data in the desired format, which you can then serialize into an NSArray
.
An example:
UIImage *someImage = ...;
NSData *someImageData = UIImagePNGRepresentation(someImage);
[yourArray addObject:someImageData];
//...
[[NSUserDefaults standardUserDefaults] setObject:yourArray forKey:@"images"];
Persist Array of Images Swift
The error message is clear actually. UIImage is not a propertylist so you need to change it to a row data first. I'll put example below but FYI saving big data like images using NSUserDefaults is really not recommended. I'd use NSFileManager and put it in the user documents directory. anyway
var newPhotoKey = DefaultsKey<NSArray>("image")
cardImages = [(UIImage(named: "MyImageName.jpg")!)]
var cardImagesRowdataArray: NSData = []
for image in cardImages {
let imageData = UIImageJPEGRepresentation(image, 1.0)
cardImagesRowdataArray.append(imageData)
}
Defaults[theKeyForStoringThisArray] = cardImagesRowdataArray
var arrayToRetreiveWith = Defaults[theKeyForStoringThisArray] as! [NSData]
// here you can use UIImage(data: data) to get it back
If you don't insist on using SwiftyUserDefaults, you can save it in the user documents directory, here is how to do it
func saveImage(image: UIImage){
if let imageData = UIImageJPEGRepresentation(image, 1.0) {
let manager = NSFileManager()
if let docUrl = manager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first{
let uniqueName = NSDate.timeIntervalSinceReferenceDate()
let url = docUrl.URLByAppendingPathComponent("\(uniqueName).jpg")
imageData.writeToURL(url, atomically: true)
}
}
}
Related Topics
Swift3: Live Uilabel Update on User Input
Coretelephony Esim Functions Not Working on Device
iOS PDFkit Displaymode = Singlepage Only Shows the First Page of the PDF
How to Make Uiscrollview Zoom in Only One Direction When Using Auto Layout
Changing Constraint When Keyboard Appears - Swift
Scrolling in Uicollectionview Selects Wrongs Cells - Swift
Get Section Number in Custom Cell Button Action
Swift/iOS Refreshing App Data When in Background
Swift - Set Delegate for Singleton
Create Alert Function in All View Controllers - Swift
Retrieving Uiimage from Uiimageview in Swift
Clipping Sound with Opus on Android, Sent from iOS
Updating the Status Bar Style Between View Controllers
Invert Calayer Mask That Is Based on a Stroke (No Fill)
Running an iOS7 Project Under Xcode 6 - Image Assets Don't Show Up