Lovely Lovely - 1 year ago 143
Objective-C Question

NSURLSession request and response

I want an example to understand how "GET" request are made using NSURLSession in objective C and how response is obtained?

Answer Source


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);
[dataTask resume];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download