Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSURLSession request and response

To understand how GET requests are made using NSURLSession in Objective-C, I would like an example. And, how is a response obtained?

like image 326
FreshStar Avatar asked Oct 13 '16 08:10

FreshStar


1 Answers

GET

NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"give your url here"]];

//create the Method "GET" 
[urlRequest setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];

NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
  NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
  if(httpResponse.statusCode == 200)
  {
    NSError *parseError = nil;
    NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
    NSLog(@"The response is - %@",responseDictionary);
  }
  else
  {
    NSLog(@"Error");     
  }
}];
[dataTask resume];
like image 100
user3182143 Avatar answered Dec 16 '22 11:12

user3182143