Database Reference
In-Depth Information
NSLog(@"City: %@", [postalCode valueForKey:@"placeName"]);
NSLog(@"County: %@", [postalCode valueForKey:@"adminName2"]);
NSLog(@"State: %@", [postalCode valueForKey:@"adminName1"]);
NSString *latitudeString =
[postalCode valueForKey:@"lat"];
NSString *northSouth = @"N";
if ([latitudeString characterAtIndex:0]== '-') {
northSouth = @"S";
latitudeString =
[latitudeString substringFromIndex:1];
}
float latitude = [latitudeString floatValue];
NSLog(@"Latitude: %4.2f%@",latitude, northSouth);
NSString *longitudeString =
[postalCode valueForKey:@"lng"];
NSString *eastWest = @"E";
if ([longitudeString characterAtIndex:0]== '-') {
eastWest = @"W";
longitudeString =
[longitudeString substringFromIndex:1];
}
float longitude = [longitudeString floatValue];
NSLog(@"Longitude: %4.2f%@", longitude, eastWest);
}
}
So, what have we got going on here? The request side is pretty straightforward: we
generate a URL endpoint (the generator does pretty much what you'd expect it to do),
and submit the request. When we get a response back, we check for error, and then
use a method in the NSJSONSerialization class called JSONObjectWithData to parse the
JSON.
The iOS 5 JSON implementation uses dictionaries, arrays, and strings to store the
parsed JSON values. We look for the postalcodes value in the top level dictionary,
which should contain an NSArray of postal codes. If we find it, we iterate over the array,
and pluck out the individual values, printing them to the log. There's even a little extra
code to turn the latitude and longitude into more human-readable versions with E/W
and N/S values.
There's only one problem with the code as currently written: it will throw an exception
when you run it. If you look closely at the original JSON, you'll see that's because the
lat and lng values don't have double quotes around them. As a result, the objects that
will be put into the dictionary for them will be NSDecimalNumber objects, not NSString .
Thus, all the string manipulation code will fail. We can fix the problem easily enough:
NSDecimalNumber *latitudeNum =
[postalCode valueForKey:@"lat"];
float latitude = [latitudeNum floatValue];
NSString *northSouth = @"N";
if (latitude < 0) {
northSouth = @"S";
latitude = - latitude;
 
Search WWH ::




Custom Search