Sorix / CloudCore

Framework that enables syncing between iCloud (CloudKit) and Core Data
MIT License
153 stars 40 forks source link

Error saving an UIImage #19

Closed jbocio closed 6 years ago

jbocio commented 6 years ago

When I try to save in CoreData a record with a transformable field using UIImage, there is an error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Objects of class UIImage cannot be set on CKRecordValueStore'

How can I solve it?

Christian1313 commented 6 years ago

Only the types are allowed for CKRecordValues:

https://developer.apple.com/documentation/cloudkit/ckrecordvalue

You have to transform the UIImage to Data (NSData) and store this in your CoreData Database.

extension UIImage {
    var imageData: Data? {
         if let d = UIImagePNGRepresentation(self) { return  d }
         return nil
    }
}
jbocio commented 6 years ago

Thanks, I've seen the binary type at the example and I was trying now, when I received your answer...

Sorix commented 6 years ago

I haven't deeply tested in with Transformable, because I use extensions for NSManagedObject with setters and getters I think it is more modern approach.

Let's create editable image attribute for our Example application:

extension Employee {

    // photoData is attribute with binary type
    // @NSManaged public var photoData: Data?

    var image: UIImage? {
        get {
            guard let imageData = self.photoData else { return nil }
            return UIImage(data: imageData)
        }
        set {
            if let newImage = newValue {
                self.photoData = UIImagePNGRepresentation(newImage)
            } else {
                self.photoData = nil
            }
        }
    }

}

Now you can work directly with native UIImage type.