8

Im trying to get Data from google distance api using NSURLSession but as seen below in code when i print response and data, i get the results as NULL. What can be the issue? or is there any other better way of fetching JSON data.

NSString *urlAsString = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&mode=bicycling&language=fr-FR&key=API-KEY"];

NSURL *url = [NSURL URLWithString:urlAsString];


NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

[[session dataTaskWithURL:[NSURL URLWithString:urlAsString]
            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

                NSLog(@"RESPONSE: %@",response);
                NSLog(@"DATA: %@",data);


            }] resume];
Mukul More
  • 554
  • 2
  • 5
  • 18

3 Answers3

11

You should use stringByAddingPercentEscapesUsingEncoding: on your url string, this is why you didn't get a response : the server returned an error.

You should have checked the error ;)

I replaced your API key in URL string, remember to put your own if you copy/paste my code :)

NSString *urlAsString = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&mode=bicycling&language=fr-FR&key=YOUR-API-KEY"];

NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
NSString *encodedUrlAsString = [urlAsString stringByAddingPercentEncodingWithAllowedCharacters:set];

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

[[session dataTaskWithURL:[NSURL URLWithString:encodedUrlAsString]
        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

    NSLog(@"RESPONSE: %@",response);
    NSLog(@"DATA: %@",data);

    if (!error) {
        // Success
        if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
            NSError *jsonError;
            NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];

            if (jsonError) {
                // Error Parsing JSON

            } else {
                // Success Parsing JSON
                // Log NSDictionary response:
                NSLog(@"%@",jsonResponse);
            }
        }  else {
            //Web server is returning an error
        }
    } else {
        // Fail
        NSLog(@"error : %@", error.description);
    }
}] resume];
Niko
  • 3,412
  • 26
  • 35
3

You might get a really good hint if you print out what's returned in the error parameter.

I.E.:

NSString *unencodedURLString = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&mode=bicycling&language=fr-FR&key=API-KEY"];
NSString *encodedURLString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
                        NULL,
                        (CFStringRef)unencodedURLString,
                        NULL,
                        (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                        kCFStringEncodingUTF8 );

[[session dataTaskWithURL:[NSURL URLWithString:encodedURLString]
            completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

    if (error != nil)
    {
       // if there's an error, print it out...
       NSLog(@"error in NSURLSession is %@", [error localizedDescription]);
    } else {
       NSLog(@"RESPONSE: %@",response);
       NSLog(@"DATA: %@",data);
    }
}] resume];

The URL encoding routine I'm using is found here.

Community
  • 1
  • 1
Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
0

From the Documentation:

The url must be in the format:

https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&key=YOUR_API_KEY

You are requesting:

origins: Vancouver+BC|Seattle
destinations: San+Francisco|Victoria+BC
mode: driving
key: API_KEY

For Transit:

https://maps.googleapis.com/maps/api/distancematrix/json?origins=Vancouver+BC|Seattle&destinations=San+Francisco|Victoria+BC&mode=transit&transit_mode=train&key=YOUR_API_KEY

You are requesitn:

  origins: Vancouver+BC|Seattle
destinations: San+Francisco|Victoria+BC
mode: transit
transit_mode: train
key: API_KEY
Teja Nandamuri
  • 11,045
  • 6
  • 57
  • 109