19

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?

Irfan
  • 4,301
  • 6
  • 29
  • 46
Andre Cytryn
  • 2,506
  • 4
  • 28
  • 43

4 Answers4

30

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

Shog9
  • 156,901
  • 35
  • 231
  • 235
Moxy
  • 4,162
  • 2
  • 30
  • 49
  • 12
    For AFN version 2.x and AFHTTPRequestOperationManager, you could do it like this: [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"]; – Itachi Aug 27 '14 at 10:29
28
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];

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

[AFJSONRequestOperation JSONRequestOperationWithRequest: request ...]
jamesmortensen
  • 33,636
  • 11
  • 99
  • 120
Mr Bonjour
  • 3,330
  • 2
  • 23
  • 46
8

I did this :)

[manager.requestSerializer setValue:[NSString stringWithFormat:@"Token token=\"%@\"", _userObj.oAuth] forHTTPHeaderField:@"Authorization"];
Serge Pedroza
  • 2,160
  • 3
  • 28
  • 41
3

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"];
Vladimir Stazhilov
  • 1,956
  • 4
  • 31
  • 63