How to add custom header to AFNetworking on a JSONRequestOperation

Andre Cytryn picture Andre Cytryn · Feb 28, 2013 · Viewed 30.8k times · Source

Hi, I have the following code accessing a URL:

NSString * stringURL = [NSString stringWithFormat:@"%@/%@/someAPI", kSERVICE_URL, kSERVICE_VERSION];
NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:stringURL]];

AFJSONRequestOperation * operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    completionHandler(JSON, nil);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
    completionHandler(nil, error);
}];

But I want to pass the user token as a parameter on HEADER, like X-USER-TOKEN.

Cant find it on AFNetworking documentation, should I change the operation type?

Answer

Moxy picture Moxy · Feb 28, 2013

Use AFHTTPClient or subclass it!

You can set default headers with -setDefaultHeader:value: like this :

[self setDefaultHeader:@"X-USER-TOKEN" value:userToken];

You can check the documentation