简体   繁体   中英

AFNetworking upload image using AFHTTPClient

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

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) {

   }];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM