2016-01-21 134 views
6
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標準?AFNetworking 3.0多部分請求

回答

6

使用POST:parameters:constructingBodyWithBlock:progress:success:failure:引用(如果不需要它,則爲progress提供nil)。

您不需要設置AcceptContent-Type標題類型。這些分別由AFJSONResponseSerializerAFJSONRequestSerializer設置。

+0

我如何使用@Stefan代碼進行圖像下載? –

+0

@ios開發人員,您可以使用AFNetworking + UIImageView中的AFNetworking方法setImageWithUrl – Stefan