Search code examples
iphoneiosobjective-cafnetworkingafnetworking-2

AFNetworking 2.0 add headers to GET request


I've just started using AFNetworking 2.0 and I was wondering how I put in headers into a HTTP Get request. The documentation sets up a GET like this:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": @"bar"};
[manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];

But since we're not handling NSURLRequests I'm not sure how to set HTTP Headers.

Any help would be appreciated.
Regards,
Mike


Solution

  • The fantastic documentation for AFNetworking 2.0 makes this a little hard to find, but it is there. On the AFHTTPRequestSerializer is -setValue:forHTTPHeaderField:.

    Alternatively, if you follow their recommended approach of creating a session manager that derives from AFHTTPSessionManager then that class can override a method to modify headers on each request -dataTaskWithRequest:completionHandler:. I use this to inspect requests and modify headers on a case-by-case basis, and prefer it to modifying the serializer as it keeps the responsibility for networking contained in that manager (and avoids mucking with singletons)

    - (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLResponse *, id, NSError *))completionHandler
    {
        static NSString *deviceId;
        if(!deviceId)
        {
            deviceId = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        }
    
        NSMutableURLRequest *req = (NSMutableURLRequest *)request;
        // Give each request a unique ID for tracing
        NSString *reqId = [NSString stringWithFormat:@"%@+%@", deviceId, [[NSUUID UUID] UUIDString] ];
        [req setValue:reqId forHTTPHeaderField:"x-myapp-requestId"];
        return [super dataTaskWithRequest:req completionHandler:completionHandler];
    }