我使用 setObject forKey 创建了一个包含数组和字符串以及其他客户端信息的 NSDictionary。当我 NSLog 数据时,一切看起来都很棒,格式正是它应该的方式。我还将我的 NSDictionary 转换为 NSData:
NSData *userData = [NSJSONSerialization dataWithJSONObject:userDict options:NSJSONWritingPrettyPrinted error:&error];
我需要知道的是如何使用 POST 将其上传到服务器。我找到了以下代码片段来上传照片。我的问题是我可以简单地使用我的 NSDictionary 作为参数(请求中的参数),它有点大。如果没有,我该如何发送我的 NSData 对象 userData?我真的很喜欢 AFNetworking,并且一直使用它来满足我所有的下载需求。这是我第一次上传对象。谢谢
NSData *imageData = UIImagePNGRepresentation(pageImage);
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://www.SERVER.com"]];
//You can add POST parameteres here
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
author, @"author",
title, @"title",
nil];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:@"/PATH/TO/WEBSERVICE.php" parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
//This is the image
[formData appendPartWithFileData: imageData name:@"cover_image" fileName:@"temp.png" mimeType:@"image/png"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
//Setup Upload block to return progress of file upload
[operation setUploadProgressBlock:^(NSInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
float progress = totalBytesWritten / (float)totalBytesExpectedToWrite;
NSLog(@"Upload Percentage: %f %%", progress*100);
}];
//Setup Completeion block to return successful or failure
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *response = [operation responseString];
NSLog(@"response: [%@]",response);
//Code to run after webservice returns success response code
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error: %@", [operation error]);
//Code to Run if Failed
}];
[operation start];