无法使用Afnetworking在SignUp POST请求中保存图片

时间:2017-07-03 06:04:42

标签: ios objective-c afnetworking ios10

我正在尝试使用AFNetworking在服务器上使用Multiparts上传图片。我试图在没有Image的情况下发出一个简单的POST请求,它工作正常。现在,可以说服务URL绝对没问题,并且服务器没有问题,我可以看到保存在文档目录中的图像URL也很好,所有其他参数都很好,因为它们都处理简单的请求。有人能在我的代码中发现一些错误吗?我的代码是:

 (void)uploadPicture:(NSMutableDictionary *)param
 {


NSString *string=[NSString stringWithFormat:@"%@%@",base_url,@"register"];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:string parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileURL:[NSURL fileURLWithPath:getImagePath] name:@"picture" fileName:getImagePath mimeType:@"image/jpeg" error:nil];
} error:nil];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
[serializer setStringEncoding:NSUTF8StringEncoding];


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

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

                      NSLog(@"Error: %@", error);
                  } else {
                      NSLog(@"%@ %@", response, responseObject);
                      NSDictionary *dict= [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                      NSDictionary *dic=responseObject;
                      NSLog(@"");
                  }
              }];

[uploadTask resume];

}

2 个答案:

答案 0 :(得分:0)

  NSString *string=[NSString stringWithFormat:@"%@%@",base_url,@"register"];

  @autoreleasepool {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

[manager POST:strurl
    parameters:parameters
    constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
      NSMutableArray *allKeys = [[imgParameters allKeys] mutableCopy];

      for (NSString *key in allKeys) {
        id object = [imgParameters objectForKey:key];

        int timestamp = [[NSDate date] timeIntervalSince1970];
        NSString *str = [[NSString alloc] initWithFormat:@"%d", timestamp];
        NSString *ranstrin = [self randomStringWithLength:8];

        //                if ([key isEqualToString:@"image"]) {
        str = [NSString stringWithFormat:@"TestThumb_%d_%@.jpg",
                                         timestamp, ranstrin];

        [formData appendPartWithFileData:object
                                    name:key
                                fileName:str
                                mimeType:@"image/jpeg"];
      }

    }
    progress:^(NSProgress *_Nonnull uploadProgress) {

    }
    success:^(NSURLSessionDataTask *_Nonnull task,
              id _Nullable responseObject) {
      complete(responseObject, nil);
    }
    failure:^(NSURLSessionDataTask *_Nullable task,
              NSError *_Nonnull error) {
      complete(nil, error);

    }];

答案 1 :(得分:0)

尝试此功能:

第一个解决方案

注意:您需要根据需要进行自定义

-(void)getResponeseWithURL:(NSString *)url WithParameter:(NSDictionary *)parameter WithImage:(UIImage *)image ImageArray:(NSMutableArray *)arrImage WithImageParameterName:(NSString *)imagename WithCallback:(void(^)(BOOL success, id responseObject))callback {
        NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@%@",BASEURL,url] parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            if (image) {
                [formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.8) name:imagename fileName:@"Image.jpg" mimeType:@"image/jpeg"];
            }
            else if (arrImage){
                int i = 1;
                for (UIImage *recipeimage in arrImage) {
                    // this condition for maintain server side coloum format : ex name , name_2 , name_3
                    [formData appendPartWithFileData:UIImageJPEGRepresentation(recipeimage, 0.8) name:i == 1 ? imagename : [NSString stringWithFormat:@"%@_%d",imagename,i] fileName:@"Image.jpg" mimeType:@"image/jpeg"];
                    i++;
                }
            }

        }error:nil];

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

        manager.responseSerializer = [AFJSONResponseSerializer serializer];

        NSURLSessionUploadTask *uploadTask;
        uploadTask = [manager
                      uploadTaskWithStreamedRequest:request
                      progress:^(NSProgress * _Nonnull uploadProgress) {
                          dispatch_async(dispatch_get_main_queue(), ^{
                          });
                      }
                      completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                          if (error) {
                              [UtilityClass showAlertWithMessage: @"Please try again" andWithTitle:@"Network Error" WithAlertStyle:AFAlertStyleFailure];

                              NSLog(@"Error: %@", [[NSString alloc]initWithData:[[error valueForKey:@"userInfo"] valueForKey:@"com.alamofire.serialization.response.error.data"] encoding:NSUTF8StringEncoding]);

                              [UtilityClass removeActivityIndicator];
                              callback(NO,nil);

                          } else {
                              callback(YES,responseObject);
                          }
                      }];

        [uploadTask resume];

}

<强>第二

您可能忘记在项目plist文件中添加ATS,因此您需要添加它。

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>