AFNetworking upload image using AFHTTPClient

143 Views Asked by At

My question is why AFHTTPClient is slow to upload image. I am using the below code for uploading

    NSData *imageToUpload = UIImageJPEGRepresentation(uploadedImgView.image, 1.0);
    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];
1

There are 1 best solutions below

8
Rahul Patel On

It might be happen that your image is large and taking time to upload Or you can use latest AFNetworking and can track progress while upload image.

NSData *imageToUpload = UIImageJPEGRepresentation(uploadedImgView.image, 1.0);
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:keyParameter, @"keyName", nil];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];

NSString *URLtoCall = @"API name as you have";

[manager POST:URLtoCall parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
[formData appendPartWithFileData:imageToUpload name:@"image" fileName:@"temp.jpeg" mimeType:@"image/jpeg"];
   } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {


   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

   }];