Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 402
Andre Cytryn Avatar asked Feb 28 '13 16:02

Andre Cytryn


3 Answers

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

like image 154
Moxy Avatar answered Nov 16 '22 13:11

Moxy


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

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

[AFJSONRequestOperation JSONRequestOperationWithRequest: request ...]
like image 28
Mr Bonjour Avatar answered Nov 16 '22 12:11

Mr Bonjour


I did this :)

[manager.requestSerializer setValue:[NSString stringWithFormat:@"Token token=\"%@\"", _userObj.oAuth] forHTTPHeaderField:@"Authorization"];
like image 8
Serge Pedroza Avatar answered Nov 16 '22 13:11

Serge Pedroza