slik slik - 3 months ago 14x
iOS Question

AFNetworking 2 how do I set a header that updates on each request

I am trying to figure out a way to update a authentication token that gets generated for each requests sent to my api.

I am currently subclassing



@interface ZXHTTPSessionManager : ZXHTTPSessionManager

+ (ZXHTTPSessionManager *)sharedClient;



#import "ZXHTTPSessionManager.h"

@implementation ZXHTTPSessionManager

+ (ZXHTTPSessionManager *)sharedClient
static ZXHTTPSessionManager *_sharedClient = nil;
static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
[config setHTTPAdditionalHeaders:@{@"User-Agent": @"MY APP"}];

_sharedClient = [[ZXHTTPSessionManager alloc] initWithBaseURL:baseURL sessionConfiguration:config];
_sharedClient.responseSerializer = [AFJSONResponseSerializer serializer];

return _sharedClient;

- (void)setAuthToken:(NSString *)token
[[self requestSerializer] setValue:token forHTTPHeaderField:@"auth_token"];


Creating a task

NSURLSessionDataTask *task = [[ZXHTTPSessionManager sharedClient] GET:@"/post"
parameters:@{ @"id" : @"123"}
success:^(NSURLSessionDataTask *task, id responseObject) {

} failure:^(NSURLSessionDataTask *task, NSError *error) {




Thanks, you helped me solve the answer to my question.

I dug more into the documentation, and read:

To change the behavior of all data task operation construction, which is also used in the GET / POST / et al. convenience methods, override dataTaskWithRequest:completionHandler:

- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request
                            completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
    // Do custom
    return [super dataTaskWithRequest:request completionHandler:completionHandler];