12

我正在更新ASIHTTPRequestAFNetworking. 就我而言,我将一组数据发送到API,这些数据是不同的类型:图像和其他。

这是我目前采用的代码,实现 API 客户端,请求共享实例,准备 params 字典并将其发送到远程 API:

NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setValue:@"Some value" forKey:aKey];

[[APIClient sharedInstance]
 postPath:@"/post"
 parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
     //some logic


 } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     //handle error

 }];

当我想将图像添加到params字典时会发生什么情况?

使用ASIHTTPRequest,我曾经执行以下操作:

NSData *imgData = UIImagePNGRepresentation(anImage);

NSString *newStr = [anImageName stringByReplacingOccurrencesOfString:@"/"
                                                              withString:@"_"];



[request addData:imgData
    withFileName:[NSString stringWithFormat:@"%@.png",newStr]
  andContentType:@"image/png"
          forKey:anOtherKey];

我深入研究了AFNetworking文档,发现他们以这样的方式附加图像NSMutableRequest

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"];
}];

我应该如何以一种巧妙的方式将它们混合在一起以将我的图像数据集成到APIClient请求中?提前谢谢。

4

2 回答 2

19

我使用相同的 AFNetworking 上传带有一些参数的图像。这段代码对我来说很好。可能会有所帮助

NSData *imageToUpload = UIImageJPEGRepresentation(uploadedImgView.image, 1.0);//(uploadedImgView.image);
if (imageToUpload)
{
    NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:keyParameter, @"keyName", nil];

    AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://------"]];

    NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:@"API name as you have" parameters:parameters constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
        [formData appendPartWithFileData: imageToUpload name:@"image" fileName:@"temp.jpeg" mimeType:@"image/jpeg"];
    }];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSDictionary *jsons = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
         //NSLog(@"response: %@",jsons);

     }
                                     failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         if([operation.response statusCode] == 403)
         {
             //NSLog(@"Upload Failed");
             return;
         }
         //NSLog(@"error: %@", [operation error]);

     }];

    [operation start];
}

祝你好运 !!

于 2013-05-22T13:02:25.473 回答
9

使用 AFNetworking 2.0.1,此代码对我有用。

-(void) saveImage: (NSData *)imageData forImageName: (NSString *) imageName {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    NSString *imagePostUrl = [NSString stringWithFormat:@"%@/v1/image", BASE_URL];
    NSDictionary *parameters = @{@"imageName": imageName};

    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:imagePostUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData name:@"image" fileName:imageName mimeType:@"image/jpeg"];
    }];

    AFHTTPRequestOperation *op = [manager HTTPRequestOperationWithRequest:request success: ^(AFHTTPRequestOperation *operation, id responseObject) {
        DLog(@"response: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        DLog(@"Error: %@", error);
    }];
    op.responseSerializer = [AFHTTPResponseSerializer serializer];
    [[NSOperationQueue mainQueue] addOperation:op];
}

如果需要 JSON 响应,请使用:

op.responseSerializer = [AFJSONResponseSerializer serializer];

代替

op.responseSerializer = [AFHTTPResponseSerializer serializer];
于 2013-10-25T23:27:22.673 回答