Search code examples
objective-cjsonnsdictionarygoogle-geocoder

Getting objectForKey: in an NSDictionary with JSON data returning nil even though the key is present


I'm making an iPhone app in which I retrieve JSON data from http://maps.googleapis.com/maps/api/geocode/json?address=canada&sensor=true, and then I store it in an NSDictionary object. My code compiles fine, and the JSON data is valid. However, when I look for certain keys, it returns nil even though the key is present and I'm not making a typo. This is the only key that works (feed is an NSDictionary object):

NSString *status = [[NSString alloc] initWithFormat:[feed objectForKey:@"status"]];

but when I do something like this:

NSString *longName = [[NSString alloc] initWithFormat:[feed objectForKey:@"long_name"]];

I get this error:

WebKit discarded an uncaught exception in the webView:shouldInsertText:replacingDOMRange:givenAction: delegate: * -[NSPlaceholderString initWithFormat:locale:arguments:]: nil argument

I have two questions: how can I fix this? Also, since this Google Geocoder can return multiple places if multiple places with the same name exist (i.e. "Springfield"), how can I choose which key I want to refer to? (like which "long_name", which "lat", etc…)

Thanks in advance!


Solution

  • The reason "status" works is because it is located at the root of your dictionary, whereas the long name and most other parts are in sub-dictionaries within sub-arrays. Try something like this instead:

    NSArray *results = [feed objectForKey:@"results"];
    NSDictionary *firstResult = [results objectAtIndex:0];
    NSArray *addressComponents = [firstResult objectForKey:@"address_components"];
    NSDictionary *firstAddress = [addressComponents objectAtIndex:0];
    NSString *longName = [firstAddress objectForKey:@"long_name"];
    

    If you want to get all of the values under hear you will of course need to set up loops - The example I've given shows how to get the long name from the first address within the first result returned.