如何通过填充NSDictionary以JSON格式发送UIImage

我想用JSON发送数据到服务器。 我能够创build我的NSDictionary与我的对象和关键参数。 但我想发送我的照片,图片是UIImage。

NSDictionary* mainJSON = [NSDictionary dictionaryWithObjectsAndKeys: @"John", @"First_Name", @"McCintosh", @"Last_name", <HERE I WANT PICTURE>, @"Profile_picture", nil]; // 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:) withObject:data waitUntilDone:YES]; } ); 

所以我想知道如何添加我的照片在我的NSDictionary? 因为我想发送我的照片的内容。 如果我添加我的对象UIImage …我会发送整个对象吗?

谢谢

您应该将UIImage转换为NSString。 使用名为NSDataAdditions的NSData的类别。您可以在这里find: NSDataAdditions类别

如何使用:

 //Convert an Image to String UIImage *anImage; NSString imageString = [UIImagePNGRepresentation(anImage) base64Encoding]; //To retrieve NSData *data = [NSData dataWithBase64EncodedString:imageString]; UIImage *recoverImage = [[UIImage imageWithData:data]; 

我通常不会使用JSON发布图片。 虽然在技术上可以将图像编码成文本,但我不认为这是如何使用JSON,我个人会避免这种做法。

处理图像作为NSData。 他们就是这样。 网上有大量的例子来说明如何做到这一点 。

一种常见的方法是将图像上传到Web服务器,然后获取上传图像的URL并将其添加到JSON字典中,以便您提交的JSON字典携带一个代表要下载的图像的URL的string – 而不是图像本身。

你可以尝试像这样用NSString发送UIImage:Swift 3:

 if let jpegData = UIImageJPEGRepresentation(image, 1.0) { var encodedString = jpegData.base64EncodedString() var mainJSON = [ "First_Name" : "John", "Last_name" : "McCintosh", "Profile_picture" : encodedString ] } 

Objective-C的:

 NSData *imageData = UIImageJPEGRepresentation(image, 1.0); NSString *encodedString = [imageData base64Encoding]; NSDictionary* mainJSON = [NSDictionary dictionaryWithObjectsAndKeys: @"John", @"First_Name", @"McCintosh", @"Last_name", encodedString, @"Profile_picture", nil]; 

这是Base64格式,所以你可以用任何语言解码

好吧,Thansk @tolgamorf和@isaac,我尝试使用AFNetwork。 我可以做我想做的。 它强大而简单。

 NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"]; AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url]; NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5); NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) { [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"]; }]; AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) { NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite); }]; [httpClient enqueueHTTPRequestOperation:operation]; 

我从这里的官方文档中获取代码。

请享用