Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading an image using AFNetworking 3.0

I tried to upload the image with using AFNetworking3.0. I have tried to find how to upload image from all stackoverflow and tutorial, but all of these are relative with AFNetworking2.0 and below. The main focus is that I am going to upload the image to the web site.

Once the image is uploaded, the image url should be existed on web site.

Please see the code below.

AFHTTPRequestOperationManager *requestManager;

[requestManager POST:KAPIUploadOutfit parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) 
{
        [formData appendPartWithFileURL:fileURL name:@"photo_url" fileName:filename mimeType:@"image/png" error:nil];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        successCB(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        errorCB(CONNECTION_ERROR);
    }];

I am not sure what the parameter is about. Please tell me how to do it.

like image 587
Marcelo P. Avatar asked Mar 11 '16 19:03

Marcelo P.


1 Answers

NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
} error:nil];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
          uploadTaskWithStreamedRequest:request
          progress:^(NSProgress * _Nonnull uploadProgress) {
              // This is not called back on the main queue.
              // You are responsible for dispatching to the main queue for UI updates
              dispatch_async(dispatch_get_main_queue(), ^{
                  //Update the progress view
                  [progressView setProgress:uploadProgress.fractionCompleted];
              });
          }
          completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
              if (error) {
                  NSLog(@"Error: %@", error);
              } else {
                  NSLog(@"%@ %@", response, responseObject);
              }
          }];

[uploadTask resume];

In this code http://example.com/upload is api where image is going to upload and file://path/to/image.jpg is your local image path.

like image 109
iVarun Avatar answered Oct 20 '22 17:10

iVarun