Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AFNetworking 3.0 multipart request

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);
    }];

This method is working fine, but constructingBodyWithBlock is deprecated. How can I optimize code to conform AFNetworking 3.0 standards?

like image 679
Stefan Avatar asked Jan 21 '16 16:01

Stefan


1 Answers

Use the POST:parameters:constructingBodyWithBlock:progress:success:failure: rendition (supplying nil for progress if you don't need it).

You do not need to set the Accept and Content-Type header types. Those are set by the AFJSONResponseSerializer and AFJSONRequestSerializer, respectively.

like image 129
Rob Avatar answered Nov 20 '22 12:11

Rob