AFHTTPSessionManager add body to POST

DaSilva picture DaSilva · Oct 10, 2014 · Viewed 24k times · Source

I need too make a post request to my server.

With AFHTTPRequestOperation is very simple just use:

[request setHTTPBody: [requestBody dataUsingEncoding:NSUTF8StringEncoding]];

However i can't find any example how use the same approach using the AFHTTPSessionManager.

Using the method:

[self POST:@"extraLink" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

} success:^(NSURLSessionDataTask *task, id responseObject) {

} failure:^(NSURLSessionDataTask *task, NSError *error) {

}];

How i add the the body to the "AFMultipartFormData"?

Thanks in advace

Answer

Rob picture Rob · Oct 10, 2014

As taken from the AFNetworking home page, to create a multipart/form-data request, you call appendPartWithFileURL:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileURL:filePath name:@"image" error:nil];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

But AFHTTPRequestOperationManager is deprecated. So, instead, use AFHTTPSessionManager, for which the syntax of POST with the constructingBodyWithBlock is very similar:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"];
[manager POST:@"http://example.com/resources.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    [formData appendPartWithFileURL:filePath name:@"image" error:nil];
} progress:nil success:^(NSURLSessionDataTask *operation, id responseObject) {
    NSLog(@"Success: %@", responseObject);
} failure:^(NSURLSessionDataTask *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

Alternatively, if you want to post a request of the form foo=bar&key=value&... (i.e. an application/x-www-form-urlencoded request), you would do something like:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *parameters = @{@"foo": @"bar", @"key": @"value"};
[manager POST:@"http://example.com/resources.json" parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
    NSLog(@"Success: %@", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
    NSLog(@"Error: %@", error);
}];