Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when trying to save image in NSUserDefaults using Swift

When i try to save an image in NSUserDefaults, the app crashed with this error.

Why? Is it possible to save an image with NSUserDefaults? If not, then how do I save the image?

Image...

Xcode error

Code...

var image1:UIImage = image1

var save1: NSUserDefaults = NSUserDefaults.standardUserDefaults()

save1.setObject(Info.Image1, forKey: "Image1")       

save1.synchronize()

Log error...

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

like image 684
nachshon f Avatar asked Apr 01 '15 23:04

nachshon f


1 Answers

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

like image 68
nhgrif Avatar answered Oct 21 '22 10:10

nhgrif