Getting JSON data using NSURLSession
11,036
Solution 1
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];
Solution 2
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.
![Mukul More](https://i.stack.imgur.com/wJxHE.jpg?s=256&g=1)
Author by
Mukul More
Always looking for the best solutions and dancing around after finding them.
Updated on June 19, 2022Comments
-
Mukul More about 2 years
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 over 8 yearsits says unsupported URL.but if i run the same url on browser i see the json data.
-
njzk2 over 8 years@Rusty well, there you have it.
-
Mukul More over 8 years@njzk2 i didn't understand.
-
Mukul More over 8 yearsyeah 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?
-
njzk2 over 8 yearsIt probably has to do with URL encoding your parameters
-
Mukul More over 8 yearsi have the same url ..still it says unsupported url
-
Teja Nandamuri over 8 yearstry removing the language tag you have in your url
-
Teja Nandamuri over 8 yearsim not sure if API key have dashes in it. Also check if your api key is correct or not.
-
Teja Nandamuri over 8 yearsdid you check the link in the POSTMan plugin in chrome ? See if you get any json data in there
-
Mukul More over 8 yearsthanks! encoding has worked..but the way you have encoded is deprecated iOS 9 onwards.
-
Mukul More over 8 yearsHow 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
-
Teja Nandamuri over 8 yearsthere is parameter called origins, and you can send coordinates like: origins=Bobcaygeon+ON|41.43206,-81.38992