Abs3akt Abs3akt - 18 days ago 5
iOS Question

How to change sendSynchronousRequest:urlRequest because is Deprecated

I'm starter in Objective - C, I have a method

- (void)getAltitudeFromElevationFromAlt:(float)latitude Long:(float)longitude{
dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *apiKey = @"IzaSyA5CDPUYC7GY5PzJdu_K4ouRy55gm3R5BO4";
NSString *address = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/elevation/json?locations=%f,%f&key=%@", latitude, longitude, apiKey];
// Send a synchronous request

NSURLRequest * urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:address]];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];

NSString *str = @"No Data";
if (error == nil)
{
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
str = [NSString stringWithFormat:@"%@", dictionary[@"results"][0][@"elevation"]];
// NSLog(@"text = %@", dictionary[@"results"][0][@"elevation"]);
NSLog(@"str = %@", str);
dispatch_async( dispatch_get_main_queue(), ^{
_altitudeMeterLabel.text = str;
});
}
});
}


please help to change this sequence

NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];

Answer

Use NSURLSession and an asynchronous request:

- (void)getAltitudeFromElevationFromAlt:(float)latitude Long:(float)longitude {

   NSString *apiKey = @"IzaSyA5CDPUYC7GY5PzJdu_K4ouRy55gm3R5BO4";
   NSString *address = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/elevation/json?locations=%f,%f&key=%@", latitude, longitude, apiKey];
   // Send an ASYNCHRONOUS request

   NSURLRequest * urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:address]];
   [[[NSURLSession sharedSession] dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
      NSString *str = @"No Data";
      if (error) {
         NSLog(@"%@", error);
      } else {
         NSError * jsonError = nil;
         NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
         if (jsonError) {
            NSLog(@"%@", jsonError);
         } else {
            str = [NSString stringWithFormat:@"%@", dictionary[@"results"][0][@"elevation"]];
            //  NSLog(@"text  = %@", dictionary[@"results"][0][@"elevation"]);
            NSLog(@"str = %@", str);
         }
         dispatch_async( dispatch_get_main_queue(), ^{
            _altitudeMeterLabel.text = str;
         });
      }
   }] resume];
}

Note:

The global dispatch_async block is not needed since the data task is dispatched to a background thread anyway.

Comments