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

3 Answers 3

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];
Sign up to request clarification or add additional context in comments.

1 Comment

thanks! encoding has worked..but the way you have encoded is deprecated iOS 9 onwards.
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.

5 Comments

its says unsupported URL.but if i run the same url on browser i see the json data.
@Rusty well, there you have it.
@njzk2 i didn't understand.
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?
It probably has to do with URL encoding your parameters
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

6 Comments

i have the same url ..still it says unsupported url
try removing the language tag you have in your url
im not sure if API key have dashes in it. Also check if your api key is correct or not.
did you check the link in the POSTMan plugin in chrome ? See if you get any json data in there
How can we pass longitude and latitude in Google Distance Matrix API request ? If i have retrieved a place using Google Places how to pass the place to Google Distance Matrix API? @Mr.T
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.