Karthik Reddy Karthik Reddy - 3 years ago 106
iOS Question

How to add Authorization in Header for Get method in objective c

I want to add my token in Authorization header

NSURL *url2 = @"";

NSLog(@"%@ urlis ====>",urlString);

NSData *data = [NSData dataWithContentsOfURL:url2];
NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *dataaa = [ret dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:dataaa options:0 error:nil];
NSArray * resultDict =[json objectForKey:@"name"];

Answer Source

You can use NSMutableRequest -

  NSURL *url2 = @"";
  NSURLSession *session = [NSURLSession sharedSession];

  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url2];

  [request setHTTPMethod:@"GET"];

  [request setValue:[[NSUserDefaults standardUserDefaults] valueForKey:@"token"] forHTTPHeaderField:@"Authorization"];
  [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

   // add any additional headers or parameters
   NSURLSessionDataTask *downloadTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (!error) {
   // do your response handling
   id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSArray * resultDict =[json objectForKey:@"name"];

  [downloadTask resume];

To understand in more detail about NSURLSession refer to this Tutorial

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download