Search code examples
core-database64cocoa-bindingsnsimageview

Base64 png with Core Data bindings


I have JSON that contains base64 decoded PNG-images that I add to Core Data. I would like to show those images in Image Wells with bindings to my Core Data model.

The problem is that I cannot use Data with NSArchiveFromData since it's been deprecated.

My problem is similar to this but I don't really understand the answer.

Does anyone have an idea?

Thanks


Solution

  • Try something to the effect of this (I'm not sure if you're just using a binding on a property, or using an NSArrayController - I'll try to answer both scenarios)

    You could take the string from your json and decode it: (You'll need the open source library referenced in the stackoverflow answer: https://stackoverflow.com/questions/14260936/decode-an-encoded-base64-image-in-c-sharp-in-objective-c)

    NSString *jsonImage = [jsonData objectForKey@"image"];
    NSData   *data      = [NSData dataWithBase64EncodedString:jsonImage];
    

    Then init your image with that data.

    If you're using an NSArrayController to manage your core data, create a value transformer that returns an image.

    Create a subclass of NSValueTransformer and name it whatever you'd like. In the implementation, add:

    +(Class)transformedValueClass {
        return [NSImage class];
    }
    -(id)transformedValue:(id)value {
        if (value == nil) {
            return nil;
        } else {
            NSData *data = [NSData dataWithBase64EncodedString:value]; //might be [value stringValue]
            return [[NSImage alloc] initWithData:data];
        }
    }
    

    Then in interface builder where you've set the binding on the image, just set the Value Transformer to the class you made.