AFNetworking 3.0多部分请求

时间:2016-01-21 16:25:49

标签: ios objective-c afnetworking

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"Bearer %@", [[NSUserDefaults standardUserDefaults] objectForKey:TOKEN]] forHTTPHeaderField:@"Authorization"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [manager POST:@"http:xxxxx" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:profileImage name:@"file" fileName:@"profileImage.jpg" mimeType:@"image/jpeg"];
    } success:^(NSURLSessionTask *task, id responseObject) {
        completionHandler(responseObject);
    } failure:^(NSURLSessionTask *operation, NSError *error) {
        NSData *errorData = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
        NSDictionary *serializedData = [NSJSONSerialization JSONObjectWithData: errorData options:kNilOptions error:nil];
        errorHandler(serializedData);
    }];

此方法运行正常,但不推荐使用constructingBodyWithBlock。如何优化代码以符合 AFNetworking 3.0 标准?

1 个答案:

答案 0 :(得分:6)

使用POST:parameters:constructingBodyWithBlock:progress:success:failure:引渡(如果您不需要nil,请提供progress)。

您无需设置AcceptContent-Type标头类型。这些分别由AFJSONResponseSerializerAFJSONRequestSerializer设置。