AFNetworking with AFJSONRequestOperation and filed

2019-05-15 23:37发布

I'm using AFNetworking to post json data to my webservice and get a json response back. However now I also want to add multipart formdata to these POST's. If I do this (even without the parameters I added first) the completion block never fires. The progress block DOES fire and I can see that the file uploads correctly.

Does anybody have any experience posting images like this with AFNetworking? I am using the latest AFNetworking source / version.

This is my initial code for posting a dictionary with json in it. This works fine.

NSMutableDictionary *postdata = [[NSMutableDictionary alloc] init];
[postdata setObject:[postdictionary JSONString] forKey:@"request"];

NSMutableURLRequest *jsonRequest = [httpClient requestWithMethod:@"POST"
                                           path:path
                                     parameters:postdata];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:jsonRequest success:^(NSURLRequest *request,     NSHTTPURLResponse *response, id JSON) {// Success} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {// Failure }];

[operation start];

This is the version of the code for submitting an image (doesn't work)

NSMutableURLRequest *jsonRequest jsonRequest = [httpClient   multipartFormRequestWithMethod:@"POST" path:path parameters:postdata constructingBodyWithBlock: ^(id <AFMultipartFormData> formData) {
    [formData appendPartWithFileData:imageData name:@"photo" fileName:@"photo.jpg" mimeType:@"image/jpeg"];
    [formData throttleBandwidthWithPacketSize:5000 delay:0.1];
}];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:jsonRequest];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long  totalBytesWritten, long long totalBytesExpectedToWrite) {
    NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Upload succes");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Upload failed");
}];

[operation start];

2条回答
唯我独甜
2楼-- · 2019-05-16 00:28

I use this code on a number of apps and havent had any problems with it (note I am using the AFJSONRequestOperation and AFRestClient)

set the request

// I have a shared singleton in a separate file APIClient.h 
AFRESTClient *httpClient = [APIClient sharedClient];

NSURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:method parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData> formData) 
    {[formData appendPartWithFileData:imageData
               name:@"image"
               fileName:@"image.png"
               mimeType:@"image/png"];
    }];

then the operation,

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

my progress block

[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {

    NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
    CGFloat progress = ((CGFloat)totalBytesWritten) / totalBytesExpectedToWrite * 100;
    [SVProgressHUD showProgress:50 status:[NSString stringWithFormat:@"%0.1f %%", progress]];

}];    

success block (my API returns a stat -ok or fail, then the data (same as flickr API)

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id response) {
    NSLog(@"response string: %@", operation.responseString);
    NSString *resultStat = [response objectForKey:@"stat"];

   if ([resultStat isEqualToString:@"ok"]) {
        //success
        // do something with your data that is returned from the API 
   } else {
        //error 
        NSLog(@"Data Error: %@", response);
   }   

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", [error localizedDescription]); 
}];

[httpClient enqueueHTTPRequestOperation:operation];
查看更多
贪生不怕死
3楼-- · 2019-05-16 00:31

cannot see any issues with your code, few possibilities:

try setting short timeout interval and check if request completes [request setTimeoutInterval:5];

also try commenting out the throttling line and see if it changes anything

查看更多
登录 后发表回答