Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


How to set Http header Fields in Objective C?

I want to call web service in Objetive C which returning Json data and I have to pass an App-Key in header to the server, any idea?


The answer is this for anyone that need it in the future...

   NSURL *theURL = [NSURL URLWithString:@"yourURL"];
   NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL      cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0f];

   //Specify method of request(Get or Post)
   [theRequest setHTTPMethod:@"GET"];

    //Pass some default parameter(like content-type etc.)
   [theRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
   [theRequest setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];

   //Now pass your own parameter

   [theRequest setValue:yourValue forHTTPHeaderField:theNameOfThePropertyValue];

   NSURLResponse *theResponse = NULL;
   NSError *theError = NULL;
   NSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
   NSDictionary *dataDictionaryResponse = [NSJSONSerialization JSONObjectWithData:theResponseData options:0 error:&theError];
   NSLog(@"url to send request= %@",theURL);