使用afnetworking在json有效负载中嵌入base64的正确方法

时间:2012-08-05 05:11:56

标签: iphone ios json base64 afnetworking

提前感谢任何帮助。我正在使用一个只接受json有效负载的Web服务,并且此服务已设置为提交照片。

所以我试图弄清楚在json有效载荷中嵌入图像的正确方法。这是我的方法。

//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

一切似乎都有效,我得到了json的有效载荷。注意:bas64字符串最终位于帖子正文中。

如果需要在数据前嵌入URI,是否有人知道使用此方法 - 如下所示:“file”:“data:image / jpg; base64,[base64 string]” - 我确实试过这个,但没有得到任何来自网络服务的爱,但我可能有错误的语法。

然而,Web服务不喜欢它。

为了验证编码,我将生成的字符串从nslog中删除并粘贴到在线解码器网站中,然后重新创建原始图像 - 所以看起来数据编码正确。

我可以在几天前与网络服务器管理员交谈,所以我只是在寻找验证这是一种正确的方法,或者请指出任何缺陷。我无法将服务更改为多部分编码形式,我坚持使用这种方法。

再次感谢

1 个答案:

答案 0 :(得分:3)

弄明白这一点,我想我会把答案拿出去,以防其他人遇到类似的问题。

场景 - 发布一个嵌入了base64string的照片的JSON有效负载。

我在这里发现了一个分叉版本的base64 https://github.com/l4u/NSData-Base64.git。在Matt Gallagher在2009年左右发布的原始作品中包含了另一种方法:base64EncodedStringWithSeparateLines:YES - 这就是诀窍。

//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);

}];