Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting JSON data using NSURLSession

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];
like image 809
Mukul More Avatar asked Feb 23 '16 14:02

Mukul More


2 Answers

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];
like image 185
Niko Avatar answered Sep 23 '22 02:09

Niko


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.

like image 33
Michael Dautermann Avatar answered Sep 25 '22 02:09

Michael Dautermann