Image Uploading with AFNetworking 3.0 [closed]

醉酒当歌 提交于 2019-12-11 03:56:08

问题


I am trying to upload images to server with AFNetworking 3.0.

Here is my code :

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [[manager POST:setUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
    {
        //Current date with image name
        NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss a"];
        [formData appendPartWithFileData:image name:namePara fileName:[NSString stringWithFormat:@"img_%@",[dateFormatter stringFromDate:[NSDate date]]] mimeType:@"image/png"];
        }progress:nil
        success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject)
        {
            NSLog(@"%@",responseObject);
            [GMDCircleLoader hideFromView:self.view animated:YES];
            NSMutableDictionary *dir = [[NSMutableDictionary alloc]initWithDictionary:responseObject];
            if([dir valueForKey:@"error"])
            {
                UIAlertController *alert = [[singletone sharedManager]showAlert:NSLocalizedString(@"SIGNIN", nil) :[NSString stringWithFormat: @"%@",[dir valueForKey:@"error"]] ];
                [self.parentViewController presentViewController:alert animated:YES completion:nil];
            }
            else
            {
                //Successfull
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"REGISTRATION", nil) message:[dir valueForKey:@"success"] preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * action)
                {
                    [self.navigationController popViewControllerAnimated:YES];
                }];
            [alertController addAction:ok];
            [self presentViewController:alertController animated:YES completion:nil];
            }
            NSLog(@"response object : %@",responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {                        NSLog(@"failure : %@",error.localizedDescription);
    }]resume];


It will get in success block with error : error In Image Uploading.
I have also tried from Postman to check my API response, but it's work fine from Postman. What is the problem with this code?


回答1:


Try below code and it working with AFNetworking 3.0 :

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



    manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];


    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:BaseURL parameters:<parameter dictionary> constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
                                    {

                                        if (profile_pic.length!=0) {

                                            [formData appendPartWithFileData:imageData name:@"profile_pic" fileName:@"ProfilePic" mimeType:@"image/jpeg"];
                                        }


                                    } error:nil];

    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

                  }
                  completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                      if (error)
                      {


                      }
                      else
                      {

                      }
                  }];

    [uploadTask resume];



回答2:


you try this

manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];



回答3:


You need to set requestSerializer to @"multipart/form-data" for @"Content-Type".

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];


    manager.responseSerializer=[AFJSONResponseSerializer serializer];

    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data"];
    [manager.requestSerializer setValue:contentType forHTTPHeaderField:@"Content-Type"];


    [manager POST:setUrl parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss a"];
        [formData appendPartWithFileData:image name:namePara fileName:[NSString stringWithFormat:@"img_%@",[dateFormatter stringFromDate:[NSDate date]]] mimeType:@"image/png"];


    } progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

       NSLog(@"%@",responseObject);
            [GMDCircleLoader hideFromView:self.view animated:YES];
            NSMutableDictionary *dir = [[NSMutableDictionary alloc]initWithDictionary:responseObject];
            if([dir valueForKey:@"error"])
            {
                UIAlertController *alert = [[singletone sharedManager]showAlert:NSLocalizedString(@"SIGNIN", nil) :[NSString stringWithFormat: @"%@",[dir valueForKey:@"error"]] ];
                [self.parentViewController presentViewController:alert animated:YES completion:nil];
            }
            else
            {
                //Successfull
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"REGISTRATION", nil) message:[dir valueForKey:@"success"] preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * action)
                {
                    [self.navigationController popViewControllerAnimated:YES];
                }];
            [alertController addAction:ok];
            [self presentViewController:alertController animated:YES completion:nil];
            }
            NSLog(@"response object : %@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error: %@", error.localizedDescription);

    }];



回答4:


NSData *nsdataFromBase64String = [[NSData alloc] initWithBase64EncodedString:imageBytes options:0];
NSMutableDictionary *parameters = [NSMutableDictionary dictionary];   

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:stringURL]];// Your API

    [manager POST:stringURL parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
    {
        //do not put image inside parameters dictionary as I did, but append it!
        [formData appendPartWithFileData:nsdataFromBase64String name:fIds fileName:fileN mimeType:@"image/jpeg"];

    }
    success:^(NSURLSessionDataTask *task, id responseObject)
     {
         imgRes=@"success";
         //here is place for code executed in success case
     }
    failure:^(NSURLSessionDataTask *task, NSError *error)
    {
        imgRes=@"fail";
         //here is place for code executed in error case
     }];

Works perfectly at my end

This is what you are using in Postman




回答5:


NSData *nsdataFromBase64String = [[NSData alloc] initWithBase64EncodedString:"your image as base64 encoded" options:0];

NSDictionary *parameters = [NSMutableDictionary dictionary];

parameters = [NSDictionary dictionaryWithObjectsAndKeys:@"wr34", @"delivery_company_name", @"uname", @"user_name", @"123456789", @"contact_info", @"test1342@test.com", @"email",@"123456", @"password",@"SUV", @"car_type",@"White", @"car_color",@"GJ-1AE-2255", @"car_plate_no",@"43345dw", @"car_reg_no",@"123454", @"license_no",@"Model", @"car_model",@"location", @"location",@"4.3", @"latitude",@"8.7", @"longitude",@"notes", @"deliver_terms_conditions",@"notes", @"notes", nil];

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:stringURL]];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];

[manager POST:stringURL parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
 {
     //do not put image inside parameters dictionary as I did, but append it!
     [formData appendPartWithFileData:nsdataFromBase64String name:@"ToyotaSupra" fileName:@"ToyotaSupra" mimeType:@"image/png"];

 }
      success:^(NSURLSessionDataTask *task, id responseObject)
 {
     imgRes=@"success";
     //here is place for code executed in success case
 }
      failure:^(NSURLSessionDataTask *task, NSError *error)
 {
     imgRes=@"fail";
     //here is place for code executed in error case
 }];

download the working code

https://www.dropbox.com/s/3ot6kpiqs3pn2h0/AFNetwork.zip?dl=0



来源:https://stackoverflow.com/questions/39245470/image-uploading-with-afnetworking-3-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!