Search code examples
iosafnetworking-2

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 AFHTTPSessionManager

.h

@interface ZXHTTPSessionManager : ZXHTTPSessionManager

+ (ZXHTTPSessionManager *)sharedClient;

@end

.m

#import "ZXHTTPSessionManager.h"

@implementation ZXHTTPSessionManager


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

    dispatch_once(&onceToken, ^{
        NSURL *baseURL = [NSURL URLWithString:APIBASEURL];

        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"];
}

@end

Creating a task

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

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

                               }];

Solution

  • @tiltem

    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];
    }