Andre Cytryn
Andre Cytryn

Reputation: 2705

How to add custom header to AFNetworking on a JSONRequestOperation

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?

Upvotes: 19

Views: 31230

Answers (4)

Serge Pedroza
Serge Pedroza

Reputation: 2170

I did this :)

[manager.requestSerializer setValue:[NSString stringWithFormat:@"Token token=\"%@\"", _userObj.oAuth] forHTTPHeaderField:@"Authorization"];

Upvotes: 8

Vladimir Stazhilov
Vladimir Stazhilov

Reputation: 1954

If you have a layer of abstraction, let's say APIManager, then you should do the following inside a particular method

 [[HTTPClient sharedHTTPClient].requestSerializer setValue:YOUR_KEY forHTTPHeaderField:@"X-Register"];

Upvotes: 3

Moxy
Moxy

Reputation: 4212

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

Upvotes: 30

Mr Bonjour
Mr Bonjour

Reputation: 3400

NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];

[request setValue: @"X-USER-TOKEN"  forHTTPHeaderField:@"< clientToken >"];

[AFJSONRequestOperation JSONRequestOperationWithRequest: request ...]

Upvotes: 28

Related Questions