Correct way to embed base64 in json payload using afnetworking

Thanks in advance for any help. I am working with a web service that uses only json data, and this service is configured to send photos.

So, I'm trying to figure out how to correctly insert an image into the json payload. This is my approach.

//convert image to nsdata NSData *originalPhoto = UIImageJPEGRepresentation(self.photo.image,.9); //convert the data to a base64 string using NSData+Base64 category extension (Matt Gallagher version) NSString *base64photoString = [originalPhoto base64EncodedString]; //set the string in a NSDictionary [info setValue:base64photoString forKey:@"data"]; //then pass it to AFNetworking using the httpClient 

everything works and I get the json payload. Note: the bas64 string falls into the body of the message.

Does anyone know about using this approach if the URI needs to be embedded in front of the data - something like this: "file": "data: image / jpg; base64, [base64 string]" - I tried this, but didn't get love from a web service, but I may have the wrong syntax.

however, the web service does not like this.

To check the encoding, I cut the generated string from nslog and pasted it into the website of the online decoder, and it again creates the original image, so it looks like the data was encoded correctly.

In a couple of days, before I can talk to the web server administrator, I am just looking for verification that this is the right approach or point out any shortcomings. I can’t change the service to a multi-part encoded form, I follow this approach.

thanks again

+4
source share
1 answer

Got it and thought that I would answer in case someone had a similar problem.

- place the JSON payload with the photo embedded in base64string.

I found a forked version of base64 here https://github.com/l4u/NSData-Base64.git . Including an additional method from the original work that Matt Gallagher published around 2009: base64EncodedStringWithSeparateLines: YES - that did the trick.

 //use it like this: NSData *originalPhoto = UIImageJPEGRepresentation(self.photo.image,1); NSString *base64PhotoString = [originalPhoto base64EncodedStringWithSeparateLines:YES]; //stuff it in a dictionary like this: NSMutableDictionary *info = [NSMutableDictionary dictionary]; [info setValue:base64PhotoString forKey:@"sFileData"]; //send it using AFNetworking like this: [[ClientInterface sharedInstance] postPath:submitPhoto parameters:info success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"success!"); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error:%@",error); }]; 
+3
source

All Articles