afnetworking 3.0 Migration: how to POST with headers and HTTP Body

Pranoy C picture Pranoy C · Jan 2, 2016 · Viewed 75.9k times · Source

I am trying to make a POST request which has HTTPHeader Fields and a HTTP body to the youtube API.

Previously in version 2.0 of AFNetworking, I used to do it this way which worked:

NSDictionary *parameters = @{@"snippet": @{@"textOriginal":self.commentToPost.text,@"parentId":self.commentReplyingTo.commentId}};

NSString *url = [NSString stringWithFormat:@"https://www.googleapis.com/youtube/v3/comments?part=snippet&access_token=%@",[[LoginSingleton sharedInstance] getaccesstoken]];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
   options:0
     error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

// And finally, add it to HTTP body and job done.
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];



AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer.timeoutInterval=[[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request progress:nil success:^(NSURLSessionTask *task, id responseObject) {
    NSLog(@"Reply JSON: %@", responseObject);


    }
} failure:^(NSURLSessionTask *operation, NSError *error) {
    NSLog(@"Error: %@, %@, %@, %@, %@", error, operation.responseObject, operation.responseData, operation.responseString, operation.request);

}];
[operation start];

The migration docs for version 3.0 replaces AFHTTPRequestOperationManager with AFHTTPSessionManager However I can't seem to find a HTTPRequestOperationWithRequest method for the AFHTTPSessionManager.

I tried using the constructingBodyWithBlock but it doesn't work maybe because I am not doing it correctly.

This is what I have so far which doesn't work:

NSDictionary *body = @{@"snippet": @{@"topLevelComment":@{@"snippet":@{@"textOriginal":self.commentToPost.text}},@"videoId":self.videoIdPostingOn}};

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body
   options:0
     error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
AFJSONRequestSerializer *serializer = [AFJSONRequestSerializer serializer];
serializer.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:@"timeoutInterval"] longValue];
[serializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[serializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];


[manager POST:[NSString stringWithFormat:@"https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&access_token=%@",[[LoginSingleton sharedInstance] getaccesstoken]] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

    [formData appendPartWithHeaders:nil body:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];

}  progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    NSLog(@"Reply JSON: %@", responseObject);

} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    NSLog(@"Error: %@, %@, %@, %@, %@", error, operation.responseObject, operation.responseData, operation.responseString, operation.request);

}];

Answer

Bruna Garcia picture Bruna Garcia · Jan 5, 2016

Another way to call a POST method with AFNetworking 3.0 is:

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

[manager POST:url parameters:parametersDictionary progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"success!");
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error: %@", error);
    }];

Hope it helps!