7

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];
  • 1
    why are you using stringWithFormat? – njzk2 Feb 23 '16 at 14:55
  • 1
    You may want to edit out your api key to protect yourself from service abuse. – Desdenova Feb 23 '16 at 15:02
  • You don't need that standalone "NSURL *url =" line up there. You don't use it. – Michael Dautermann Feb 23 '16 at 15:05
  • I think the issue is with URL – Vandit Mehta Feb 23 '16 at 15:53
7

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];
  • thanks! encoding has worked..but the way you have encoded is deprecated iOS 9 onwards. – Mukul More Feb 23 '16 at 15:17
  • Indeed, I've updated my code ;) – Niko Feb 23 '16 at 15:19
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.

  • its says unsupported URL.but if i run the same url on browser i see the json data. – Mukul More Feb 23 '16 at 14:52
  • @Rusty well, there you have it. – njzk2 Feb 23 '16 at 14:54
  • @njzk2 i didn't understand. – Mukul More Feb 23 '16 at 14:54
  • that's the issue you have to solve. – njzk2 Feb 23 '16 at 14:55
  • yeah i understood that ..but if the url is giving me json in browser it means that my url is correct. @njzk2 what can be the issue with the format any idea? – Mukul More Feb 23 '16 at 14:56
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
  • i have the same url ..still it says unsupported url – Mukul More Feb 23 '16 at 15:00
  • try removing the language tag you have in your url – Teja Nandamuri Feb 23 '16 at 15:00
  • im not sure if API key have dashes in it. Also check if your api key is correct or not. – Teja Nandamuri Feb 23 '16 at 15:01
  • the link is working perfectly fine in browser – Mukul More Feb 23 '16 at 15:06
  • did you check the link in the POSTMan plugin in chrome ? See if you get any json data in there – Teja Nandamuri Feb 23 '16 at 15:07

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.