Tom Hamming
Tom Hamming

Reputation: 10961

How to turn image data in JSON from WCF Data Services into UIImage in iOS

How do I get image data out of JSON returned by a WCF Data Service?

I've got a WCF Data Service serving some objects that include some binary data that is an image (column type in SQL Server is image). It comes across as text gibberish in the JSON. In the iOS client I'm writing for this service, I want to display this data as an image ([UIImage imageWitData:myData]).

Here is what I'm doing:

NSData *networkData = nil; //assume this magically gets data from the service
NSError *err = nil;
//assume the returned JSON has one object and is not an array
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:networkData
     options:NSJSONReadingAllowFragments error:&err];

//handle error if needed

NSString *imageString = [dict objectForKey:@"Image"];
NSData *imageData = [imageString dataUsingEncoding:NSUTF8StringEncoding];
///The service is using UTF-8.
UIImage *image = [UIImage imageWithData:imageData];

Putting that image in a UIImageView doesn't show anything. What am I doing wrong?

Upvotes: 2

Views: 706

Answers (1)

Tom Hamming
Tom Hamming

Reputation: 10961

Turns out that binary data returned from WCF Data Services is base64 encoded. I'm using the NSData-Base64 category to parse it, and it's working great. So the solution looks like this:

NSData imageData = [NSData dataFromBase64String:imageString];

When I imported those files into my project ARC threw up some errors, but I was able to solve them by removing a couple of autorelease calls in the .m file.

Upvotes: 2

Related Questions