Brian Love
Angular + TypeScript Developer in Denver, CO

Setting custom HTTP request headers with RestKit

Reading time ~1 minute

RestKit is a great REST framework for Objective-C whose goal is to simplify consuming and modeling of RESTful APIs.

I am using RestKit in an application that is synchronizing data between the client application and a remote server. I want to specify a custom HTTP header when sending the request to the remote server. With RestKit, it’s actually really easy, but I wanted to document it here.

This assumes that you have already performed the initialization of the RestKit client, which is an instance of the RKObject class. In my project, I am using the object manager for mapping between the data payloads and Objective-C objects, so I will get access to the client instance through the shared object manager singleton. The first step is to get access to this client:

RKObjectManager *objectManager = [RKObjectManager sharedManager];
RKClient *client = objectManager.client;

Then, it’s as simple as calling the client’s setValue:forHTTPHeaderField: method:

[client setValue:[NSString stringWithFormat:@"%d", [lastUpdated intValue]] forHTTPHeaderField:@"X-RESTKIT-LASTUPDATED"];

Here, I am using the lastUpdated NSNumber, which I am creating a string from the integer value. This is a unix timestamp that I am going to send to my REST service for determining the last time the client was updated, so I can just send the records that have been updated since then. I am setting the value for the HTTP header called “X-RESTKIT-LASTUPDATED”. Pretty easy, thanks to RestKit.

Setting HTTP Request header without using RestKit

RestKit does a nice job ofabstracting the details of using the native NSURLRequest and NSURLConnection classes. But, what if we were doing the request manually without using RestKit. Well, it’s actually still fairly easy to set a custom HTTP request header. First, we will create a new NSURLRequest, which we will use for creating the NSURLConnection.

NSString *myServerUrl = @"http://brianflove.com";
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:[myServerUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
[request setValue:[NSString stringWithFormat:@"%d", [lastUpdated intValue]] forHTTPHeaderField:@"X-LASTUPDATED"];

We then use the request object to create the NSURLConnection and fire off the request:

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

Brian Love

Hi, I'm Brian. I am interested in TypeScript, Angular and Node.js. I'm married to my best friend Bonnie, I live in Denver and I ski (a lot).