manonthemoon manonthemoon - 1 year ago 112
Objective-C Question

How to send UIImage in JSON format, by filling a NSDictionary

I'm trying to send data to a server with JSON.
I am able to create my NSDictionary with my objects and key parameters.
But I want to send my picture, and the picture is UIImage.

NSDictionary* mainJSON = [NSDictionary dictionaryWithObjectsAndKeys:

// Here I convert to NSDATA
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:mainJSON options:NSJSONWritingPrettyPrinted error:&error];

// Sending operation :
dispatch_async(kBgQueue, ^
NSData * data = [NSData dataWithContentsOfURL:@"addresSERVER"];
[self performSelectorOnMainThread:@selector(receivedResponseFromServer:)

So I'm wondering how can I add my picture in my NSDictionary?
Because I want to send the content of my picture. If I add my object UIImage... I'll send the whole object right?


Answer Source

You should convert the UIImage to NSString. Use the category of NSData called NSDataAdditions.You can find here: NSDataAdditions category

How to Use:

//Convert an Image to String
UIImage *anImage;
NSString imageString = [UIImagePNGRepresentation(anImage) base64Encoding];

//To retrieve
NSData *data = [NSData dataWithBase64EncodedString:imageString];
UIImage *recoverImage = [[UIImage imageWithData:data];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download