AFNetworking 2.0 Request w. Custom Header

ChuckKelly picture ChuckKelly · Nov 30, 2013 · Viewed 12.7k times · Source

Ive tried to avoid asking such a newb question on here, but im a Android dev learning IOS and I cant figure out for the life of me how to add a simple header to my post requests using AFNetworking 2.0. Below is my code so far which works if i want to make a request that doesnt require a header.Could anyone show me via adding to my snippet or providing a alternate one that does this? I came across this tut: http://www.raywenderlich.com/30445 that shows how to add a header under the "A RESTful Class" heading , but its for afnetworking 1.0 and is now depreciated as far as i can tell.

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{@"uid": @"1"};
    AFHT
    [manager POST:@"http://myface.com/api/profile/format/json" parameters:parameters  success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //NSLog(@"JSON: %@", responseObject);

        self.feedArray = [responseObject objectForKey:@"feed"];

        [self.tableView reloadData];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    } ];
}

Answer

simeon picture simeon · Nov 30, 2013

Under AFHTTPRequestOperationManager you will notice a property called requestSerializer. This is of type AFHTTPRequestSerializer, and requests made through the HTTP manager are constructed with the headers specified by this object.

So, try this:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

[manager.requestSerializer setValue:@"SomeValue" forHTTPHeaderField:@"SomeHeaderField"]

//Make your requests

You can read the headers dictionary from the request serializer as follows:

manager.requestSerializer.HTTPRequestHeaders

Note that once you set a header this way, it will be used for all other operations!