iosafnetworking-2nsurlrequest

Add custom header to either NSURLRequest or AFHTTPRequestOperation


I have a project that I need to add a custom header auth_token to. It's a bit unclear to me how to add to a AFHTTPRequestOperation. I have:

  NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
  // Configure Session Configuration
  [sessionConfiguration setAllowsCellularAccess:YES];
  [sessionConfiguration setHTTPAdditionalHeaders:@{ @"auth_token" : [self.credentialStore authToken]}];
  // Create Session
  NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];

  NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"%@/arc/v1/api/mi/images",MYHost()]];

  NSURLRequest *request = [NSURLRequest requestWithURL:URL];
  //[manager.requestSerializer setValue:[self.credentialStore authToken] forHTTPHeaderField:@"auth_token"];

  AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
  op.responseSerializer = [AFJSONResponseSerializer serializer];
  [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

 ...

 [[NSOperationQueue mainQueue] addOperation:op];

How would I add the auth_token as a custom header?

in other parts we use:

  AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
  [manager.requestSerializer setValue:[self.credentialStore authToken] forHTTPHeaderField:@"auth_token"];

If that's the preferred way, I can migrate code over to that style.


Solution

  • Setting it on the request serializer is the recommended method when using AFNetworking. However, it looks like you're also using NSURLSession directly. I'd recommend deciding on one networking approach before deciding where to set a custom header.