Iurceac Iurie
Iurceac Iurie

Reputation: 95

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];

Upvotes: 1

Views: 758

Answers (4)

Shrikant Tanwade
Shrikant Tanwade

Reputation: 1441

Use NSURLSession with dataTaskWithRequest

- (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];

    NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:address]];
    NSURLResponse * response = nil;
    NSString *str = @"No Data";

    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                         completionHandler:
     ^(NSData *data, NSURLResponse *response, NSError *error) {
    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;
        });
    }
    }];

     [task resume];    
}     

Upvotes: 0

PlusInfosys
PlusInfosys

Reputation: 3436

Synchronous methods are deprecated from iOS 9, because it block the main thread for that time. So its not advisable to do send execute this operation synchronously.

If really needed you can create category of NSUrlSession to execute your request synchronously.

#import "NSURLSession+Sync.h"

@implementation NSURLSession (Sync)

+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request
                 returningResponse:(__autoreleasing NSURLResponse **)responsePtr
                             error:(__autoreleasing NSError **)errorPtr {
    dispatch_semaphore_t    sem;
    __block NSData *        result;

    result = nil;

    sem = dispatch_semaphore_create(0);

    [[[NSURLSession sharedSession] dataTaskWithRequest:request
                                     completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                         if (errorPtr != NULL) {
                                             *errorPtr = error;
                                         }
                                         if (responsePtr != NULL) {
                                             *responsePtr = response;
                                         }  
                                         if (error == nil) {  
                                             result = data;  
                                         }  
                                         dispatch_semaphore_signal(sem);  
                                     }] resume];  

    dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);  

    return result;  
}
@end

and use in code like following:

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

Upvotes: 0

Yog
Yog

Reputation: 1

Please try Following Code

    - (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

    NSURLSession *session = [NSURLSession sharedSession];
    [[session dataTaskWithURL:[NSURL URLWithString:address]
            completionHandler:^(NSData *data,
                                NSURLResponse *response,
                                NSError *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;
                    });
                }

            }] resume];
    });

}

Upvotes: 0

vadian
vadian

Reputation: 285160

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.

Upvotes: 2

Related Questions