ios - 在 AFNetworking V2.0 中使用多个参数进行 POST

标签 ios objective-c afnetworking-2

我正在将一些(相当旧的)ASIHTTPRequest 代码更新到 AFNetworking V2.0。

现在我正在处理一个 POST 请求,该请求为请求上传一个带有额外参数的 NSDictionary。

这是 ASIHTTPRequest 代码的样子:

NSMutableData* mPostData = [NSMutableData dataWithData:[postData dataUsingEncoding:NSUTF8StringEncoding]];
        NSString *msgLength = [NSString stringWithFormat:@"%d", [postData length]];
        [r setPostBody: mPostData];
        [r addRequestHeader: @"Content-Length" value:msgLength];    
    }

postData 是一个具有键/值的 NSDictionary - 它基于所采取的操作。例如 - 上传图像将有额外的参数。完成用户注册将有不同的参数 - 但使用与此代码相同的方法。

委托(delegate)调用这段代码:

//Request must be ASIFormDataRequest
- (BOOL) addFileWithPath:(NSString*) filePath fileName: (NSString*)fileName ofType: (NSString*) fileType withKey: (NSString*) fileKey uploadProgressDelegate:(id) uploadProgressDelegate
{
    if ([request isKindOfClass:[ASIFormDataRequest class]])
    {
        ASIFormDataRequest *formRequest = (ASIFormDataRequest *) request;
        NSLog(@"%@ %@ %@ %@",filePath,fileName,fileType,fileKey);
        if (uploadProgressDelegate)
        {
            [formRequest setUploadProgressDelegate:uploadProgressDelegate];
        }

        NSLog(@"filename = %@",fileName);
        [formRequest setFile:filePath withFileName:fileName andContentType:fileType forKey:fileKey];
        return YES;
    }
    else
    {
        NSLog(@"WebService must be initialised with PostDataValuesAndKeys so that ASIFormDataRequest is made");
        return NO;
    }
}

现在从我所做的大量挖掘中 - 我只能看到这段 AfNwtworking 代码 - 在我看来它来自版本 1.x

NSString *urlString = @"yourUrl";  
    NSURL* url = [NSURL URLWithString:urlString];  

    AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];  
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];  
    NSURL *localVideoURL = [NSURL URLWithString:[userDefaults objectForKey:@"videoURL"]];  
    NSData *videoData = [NSData dataWithContentsOfURL:localVideoURL];  

    NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:nil parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {  
      [formData appendPartWithFileData:videoData name:@"video_file" fileName:@"testvideo.mov" mimeType:@"video/quicktime"];  
      [formData appendPartWithFormData:[[BAUserInfoParser userInfoJson] dataUsingEncoding:NSUTF8StringEncoding] name:@"userInfo"];  
      [formData appendPartWithFormData:[[userDefaults objectForKey:@"transactionReceiptData"] dataUsingEncoding:NSUTF8StringEncoding] name:@"transactionData"];  
    }];  

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];  
    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {  
      // NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);  
      float uploadPercentge = (float)totalBytesWritten / (float)totalBytesExpectedToWrite;  
      float uploadActualPercentage = uploadPercentge *100;  
      [lblUploadInfoText setText:[NSString stringWithFormat:@"%.2f %%",uploadActualPercentage]];  
      if (uploadActualPercentage >= 100) {  
        lblStatus.text = @"Waitting for response ...";  
      }  
      progressBar.progress = uploadPercentge;  
    }];  
    [httpClient enqueueHTTPRequestOperation:operation];  

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {  
  lblStatus.text = @"Upload Complete";  
   NSData *JSONData = [operation.responseString dataUsingEncoding:NSUTF8StringEncoding];  
      NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:nil];  
      }  
      failure:^(AFHTTPRequestOperation *operation, NSError *error) {  
        NSLog(@"error: %@", operation.responseString);  
        NSLog(@"%@",error);  
    }];  
    [operation start];  
  }  

AFNetworking 的第 2 版中 - 有针对此类的新的便捷方法:

这是带有额外 block 的 POST 方法..

[self.manager POST:url parameters:urlParameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {


                // postData

    }

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

            //Success

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

            //Failure
    }];

但是我对 constructingBodyWithBlock 有疑问。我不确定我需要做什么才能获取 NSDictionary 对象并将其上传到该 block 中。

最佳答案

urlParameters 应该是一个 NS 字典。因为它是一个正在上传的对象

NSDictionary *urlParameters(制作你的字典)

参数:url参数

这对我有用。

关于ios - 在 AFNetworking V2.0 中使用多个参数进行 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19765998/

相关文章:

ios - 检测 UIView/UILabel 何时重绘自身?

ios - 如何在 iOS 中从我的应用程序启动第三方应用程序?

ios - 原型(prototype)单元中的约束

ios - 如何加载 View "properly"iOS

ios - 从对类的引用实例化

objective-c - 如何从 ARC 下运行时定义的类方法返回结构值?

objective-c - UIPopoverController 内存崩溃

ios - 在 afnetworking 中为授权 token 设置请求 header

ios - AFNetworking 2.0 HTTP POST 进展

afnetworking - AFNetworking 2.0 中的 setTaskDidReceiveAuthenticationChallengeBlock