Error when trying to save image in NSUserDefaults using Swift

后端 未结 4 725
醉梦人生
醉梦人生 2020-12-06 07:00

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

4条回答
  •  無奈伤痛
    2020-12-06 08:07

    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

提交回复
热议问题