2013-05-22 23 views
12

Tôi đang cập nhật mã ứng dụng cũ đã sử dụng ASIHTTPRequest với AFNetworking. Trong trường hợp của tôi, tôi đang gửi một băng ghế dự bị dữ liệu đến API, các dữ liệu này là các loại khác nhau: Hình ảnh và hình ảnh khác.gửi hình ảnh cùng với các thông số khác với AFNetworking

Đây là mã giả đã sử dụng cho đến nay, việc thực hiện một ứng dụng API, yêu cầu một trường hợp chia sẻ, chuẩn bị từ điển params và gửi cho API từ xa:

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 

}]; 

gì sẽ là trường hợp khi tôi muốn thêm hình ảnh vào từ điển params?

Với ASIHTTPRequest, tôi sử dụng để làm như sau:

NSData *imgData = UIImagePNGRepresentation(anImage); 

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



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

tôi đào vào AFNetworking tài liệu và thấy họ phụ thêm hình ảnh trong một NSMutableRequest như thế này:

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

Làm thế nào tôi nên trộn này cùng nhau trên một cách gọn gàng để tích hợp dữ liệu hình ảnh của tôi vào yêu cầu APIClient? Thanx trước.

Trả lời

20

Tôi đã sử dụng cùng một AFNetworking để tải lên hình ảnh với một số thông số. Mã này tốt cho tôi. Có thể nó sẽ giúp đỡ

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

Chúc may mắn !!

+0

Hi, nơi nào bạn đặt 'key' cho hình ảnh? Thanx. – Malloc

+2

@ "hình ảnh" là chìa khóa cho bất kỳ hình ảnh nào bạn muốn tải lên. –

+0

Nó có giúp bạn không? –

9

Với AFNetworking 2.0.1 mã này đã hoạt động đối với tôi.

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

Nếu JSON phản ứng là cần thiết sử dụng:

op.responseSerializer = [AFJSONResponseSerializer serializer]; 

thay vì

op.responseSerializer = [AFHTTPResponseSerializer serializer]; 
+2

AFHTTPClient được chia thành [AFHTTPRequestOperationManager & AFHTTPSessionManager] (https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-2.0-Migration-Guide#afhttpclient--afhttprequestoperationmanager--afhttpsessionmanager). Nó không còn tồn tại nữa trong 2.0. – jerik

+0

cảm ơn rất nhiều! – Frade

Các vấn đề liên quan