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 标准?
答案 0 :(得分:6)
使用POST:parameters:constructingBodyWithBlock:progress:success:failure:
引渡(如果您不需要nil
,请提供progress
)。
您无需设置Accept
和Content-Type
标头类型。这些分别由AFJSONResponseSerializer
和AFJSONRequestSerializer
设置。