iOS geocoding data from google parsing json - ios

I'm pulling some data from google maps but I can't seem to do anything with it. Here's my code:
- (void)connectionDidFinishLoading:(NSURLConnection *)theConnection {
//do something with the data!
NSError *e = nil;
//parse the json data
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: receivedData options: NSJSONReadingMutableContainers error: &e];
//get the lat and long and put it into an array
locationData = [[NSMutableArray alloc] init];
NSLog(#"%#", [jsonArray objectAtIndex:0]);
}
if I log jsonArray.count I get 2, which seems right since google will return results and status at the top level. But if I try to get object 0 it crashes. If I try to do something like this it also crashes:
- (void)connectionDidFinishLoading:(NSURLConnection *)theConnection {
//do something with the data!
NSError *e = nil;
//parse the json data
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: receivedData options: NSJSONReadingMutableContainers error: &e];
//get the lat and long and put it into an array
locationData = [[NSMutableArray alloc] init];
for(NSDictionary* thisLocationDict in jsonArray) {
NSString* location = [thisLocationDict objectForKey:#"results"];
[locationData addObject:location];
}
}
I use this code to get data from Twitter with no problems. The error I get in the console is I am trying to get an object of a string:
-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x798a270
Here's the json google is sending me:
results = (
{
"address_components" = (
{
"long_name" = 2900;
"short_name" = 2900;
types = (
"street_number"
);
},
{
"long_name" = "Horizon Dr";
"short_name" = "Horizon Dr";
types = (
route
);
},
{
"long_name" = "King of Prussia";
"short_name" = "King of Prussia";
types = (
locality,
political
);
},
{
"long_name" = "Upper Merion";
"short_name" = "Upper Merion";
types = (
"administrative_area_level_3",
political
);
},
{
"long_name" = Montgomery;
"short_name" = Montgomery;
types = (
"administrative_area_level_2",
political
);
},
{
"long_name" = Pennsylvania;
"short_name" = PA;
types = (
"administrative_area_level_1",
political
);
},
{
"long_name" = "United States";
"short_name" = US;
types = (
country,
political
);
},
{
"long_name" = 19406;
"short_name" = 19406;
types = (
"postal_code"
);
}
);
"formatted_address" = "2900 Horizon Dr, King of Prussia, PA 19406, USA";
geometry = {
location = {
lat = "40.0896985";
lng = "-75.341717";
};
"location_type" = ROOFTOP;
viewport = {
northeast = {
lat = "40.09104748029149";
lng = "-75.34036801970849";
};
southwest = {
lat = "40.0883495197085";
lng = "-75.34306598029151";
};
};
};
types = (
"street_address"
);
}
);
status = OK;
}
and the url I am passing:
http://maps.googleapis.com/maps/api/geocode/json?address=2900+Horizon+Drive+King+of+Prussia+,+PA&sensor=false
any idea what I am doing wrong?

The difference from the data that you get from google is that it comes separate by keys, such as results, geometry, formatted_address...
You should do something like this:
NSError *error;
NSString *lookUpString = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?address=%#&components=country:AU&sensor=false", self.searchBar.text];
lookUpString = [lookUpString stringByReplacingOccurrencesOfString:#" " withString:#"+"];
NSData *jsonResponse = [NSData dataWithContentsOfURL:[NSURL URLWithString:lookUpString]];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonResponse options:kNilOptions error:&error];
self.locationArray = [[jsonDict valueForKey:#"results"] valueForKey:#"formatted_address"];
int total = self.locationArray.count;
NSLog(#"locationArray count: %d", self.locationArray.count);
for (int i = 0; i < total; i++)
{
NSString *statusString = [jsonDict valueForKey:#"status"];
NSLog(#"JSON Response Status:%#", statusString);
NSLog(#"Address: %#", [self.locationArray objectAtIndex:i]);
}

Related

Extract dependentLocality from CLPlacemark item

I am trying to extract the dependentLocality information that is returned in a CLPlacemark object. The data (anonymized) looks like
{
"cache_control" = CACHEABLE;
"start_index" = 0;
status = "STATUS_SUCCESS";
ttl = 15768000;
type = "COMPONENT_TYPE_ADDRESS";
value = (
{
address = {
"known_accuracy" = POINT;
"localized_address" = (
{
address = {
formattedAddressLine = (
"111 Some St",
"Brooklyn, NY 11111-1111",
"United States"
);
structuredAddress = {
administrativeArea = "New York";
administrativeAreaCode = NY;
areaOfInterest = (
"Long Island"
);
country = "United States";
countryCode = US;
dependentLocality = (
"Bedford Stuyvesant",
Brooklyn
);
fullThoroughfare = "111 Some St";
geoId = (
);
locality = "New York";
postCode = 11206;
postCodeExtension = 1111;
postCodeFull = "11111-1111";
subAdministrativeArea = Kings;
subLocality = Brooklyn;
subThoroughfare = 111;
thoroughfare = "Some St";
};
};
locale = "en_US";
}
);
};
}
);
"values_available" = 1;
version = 7;
"version_domain" = (
apple,
revgeo,
US
);
},
I can't access the contents (other than through Apple's structuredAddress property, which doesn't contain what I want). I want to extract "Bedford Stuyvesant", Brooklyn" from what's above, for instance. Have tried numerous ways around this, but eg. casting the placemark to an NSDictionary fails. Any help would be greatly appreciated!
Maybe you can do some string processing to extract dependentLocality from your placemark.description. But why don't you just use placemark.subLocality property?
NSString *geoMapItem = placemark.description;
NSRange start = [geoMapItem rangeOfString:#"dependentLocality"];
NSRange end = [geoMapItem rangeOfString:#")" options:NSCaseInsensitiveSearch range:NSMakeRange(start.location, 1000)];
NSString *dataString = [geoMapItem substringWithRange:NSMakeRange(start.location, end.location - start.location + end.length)];
dataString = [dataString stringByReplacingOccurrencesOfString:#"\n" withString:#""];
dataString = [dataString stringByReplacingOccurrencesOfString:#" " withString:#""];
dataString = [dataString stringByReplacingOccurrencesOfString:#"\"" withString:#""];
start = [dataString rangeOfString:#"("];
end = [dataString rangeOfString:#")"];
NSString *arrayString = [dataString substringWithRange:NSMakeRange(start.location + 1, end.location - start.location - 1)];
NSArray *array = [arrayString componentsSeparatedByString:#","];

Print UIImage metadata to label

I'm attempting to read the metadata produced by a UIImage when shot from the UIImagePicker, and I'm having some trouble.
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
image = [info objectForKey:#"UIImagePickerControllerOriginalImage"];
// get the metadata
NSDictionary *imageMetadata = [info objectForKey:UIImagePickerControllerMediaMetadata];
NSLog (#"imageMetaData %#",imageMetadata);
This successfully prints the metadata dictionary to NSLog.
The issue I'm having is that I would like to access specific indices of the dictionary (such as FNumber, ISO, etc.) and print them to specific labels, but I can't figure out how to access the individual data.
Here is what I have tried so far to pull the data, but it doesn't seem to find the key (it returns as NULL):
NSLog(#"ISO: %#", imageMetadata[#"ISOSpeedRatings"]);
Based off of what NSLog prints for the dictionary, it seems as if there may be dictionaries within the dictionary, and that's what's throwing me off.
Here's what gets printed for the metadata:
imageMetaData {
DPIHeight = 72;
DPIWidth = 72;
Orientation = 6;
"{Exif}" = {
ApertureValue = "2.27500704749987";
BrightnessValue = "-0.6309286396300304";
ColorSpace = 1;
DateTimeDigitized = "2015:04:01 10:33:37";
DateTimeOriginal = "2015:04:01 10:33:37";
ExposureBiasValue = 0;
ExposureMode = 0;
ExposureProgram = 2;
ExposureTime = "0.06666666666666667";
FNumber = "2.2";
Flash = 24;
FocalLenIn35mmFilm = 29;
FocalLength = "4.15";
ISOSpeedRatings = (
320
);
LensMake = Apple;
LensModel = "iPhone 6 back camera 4.15mm f/2.2";
LensSpecification = (
"4.15",
"4.15",
"2.2",
"2.2"
);
MeteringMode = 5;
PixelXDimension = 3264;
PixelYDimension = 2448;
SceneType = 1;
SensingMethod = 2;
ShutterSpeedValue = "3.907056515078773";
SubjectArea = (
1631,
1223,
1795,
1077
);
SubsecTimeDigitized = 705;
SubsecTimeOriginal = 705;
WhiteBalance = 0;
};
"{MakerApple}" = {
1 = 2;
14 = 0;
2 = <0f000b00 06000900 04005000 a900b100 b700bb00 c400cd00 cd00a400 b100c700 14000b00 05000900 06000a00 8a00a800 b000b800 c300cb00 c900cd00 b300a600 2f000700 06000700 0a000400 3500a400 ab00b300 bc00c300 cf00d300 b4007f00 3f000700 09000700 0a000700 05007100 a100af00 b500c200 ce00cd00 a9006b00 1f000a00 0b000900 0a000c00 05001e00 9c00aa00 b400c200 cc00d000 d4005700 2b001900 0d001000 10000d00 08000600 5b00a700 b300bf00 cb00d500 e3008600 eb002800 1a001700 14000c00 0b000700 10009400 b100c000 ce00e000 f400bd00 cf013e00 2a001200 17000f00 0d000800 07004200 b100c000 d300e900 fd000401 ff011101 1d000700 16001400 09000700 07000900 8900bf00 d800ec00 07011f01 10021102 39000b00 10001900 0e000800 0a000700 2c00bf00 dd00f400 0b012401 1e023802 1f010d00 07001900 16000c00 0c000800 21007000 c500f400 0a012e01 10022202 01022500 08001000 18001100 0d001800 1601cc00 d100eb00 09012201 fb011002 26020401 0f000700 16001400 3200e801 6001b000 ce00f400 08011601 e1010602 1a020302 23001700 21002300 84009300 9f00ad00 bf00e800 02011401 ca01fc01 19024002 08013d00 3500ca00 7c009200 9e00ab00 c200d700 f8000a01 b401f101 1b024802 28023000 4a007f00 7f008e00 a000b100 bd00d000 ec00fe00>;
3 = {
epoch = 0;
flags = 1;
timescale = 1000000000;
value = 777291330499583;
};
4 = 1;
5 = 128;
6 = 123;
7 = 1;
8 = (
"0.2226092",
"-0.5721548",
"-0.7796207"
);
9 = 275;
};
"{TIFF}" = {
DateTime = "2015:04:01 10:33:37";
Make = Apple;
Model = "iPhone 6";
Software = "8.1.2";
XResolution = 72;
YResolution = 72;
};
}
Is the data I'm looking for within another NSDictionary named Exif? And if so, how do I access it?
#david strauss can you try this once
- (void) saveImage:(UIImage *)imageToSave withInfo:(NSDictionary *)info{
// Get the assets library
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
// Get the image metadata (EXIF & TIFF)
NSMutableDictionary * imageMetadata = [[info objectForKey:UIImagePickerControllerMediaMetadata] mutableCopy];
// add GPS data
CLLocation * loc = <•••>; // need a location here
if ( loc ) {
[imageMetadata setObject:[self gpsDictionaryForLocation:loc] forKey:(NSString*)kCGImagePropertyGPSDictionary];
}
ALAssetsLibraryWriteImageCompletionBlock imageWriteCompletionBlock =
^(NSURL *newURL, NSError *error) {
if (error) {
NSLog( #"Error writing image with metadata to Photo Library: %#", error );
} else {
NSLog( #"Wrote image %# with metadata %# to Photo Library",newURL,imageMetadata);
}
};
// Save the new image to the Camera Roll
[library writeImageToSavedPhotosAlbum:[imageToSave CGImage]
metadata:imageMetadata
completionBlock:imageWriteCompletionBlock];
[imageMetadata release];
[library release];
}
The metadata dictionary as you've noticed consists of several dictionaries.
So to answer your question - yes, if you're looking for specific values you can access the inner dictionaries. Also, you'd better use the proper keys from ImageIO constants; for example:
NSLog(#"%#", imageMetadata[(NSString*)kCGImagePropertyExifDictionary][(NSString*)kCGImagePropertyExifISOSpeedRatings]);
Or, you can use a key-path:
NSString *keyPath = [NSString stringWithFormat:#"%#.%#",
(NSString*)kCGImagePropertyExifDictionary, (NSString*)kCGImagePropertyExifISOSpeedRatings];
NSLog(#"%#", [imageMetadata valueForKeyPath:keyPath]);
your all required data is within this dictionary only.
you can use json formatter to see the exact location of your data.
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject: imageMetadata
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"jsonString: %#", jsonString);
}
after this get the exact location of your data from json

flickr.photoset.getlist json parsing in ios

I want to parse a array of json dictionary which is returned to me using the method flickr.photosets.getlist.I am using objectiveFlickr api.
This is my json
"_text" = "\n\n";
photosets = {
"_text" = "\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t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";
"can_comment" = 1;
"count_comments" = 0;
"count_views" = 0;
"date_create" = 1403859842;
"date_update" = 0;
description = {
"_text" = "Uploaded from my iPhone/iPod Touch";
};
farm = 6;
id = 72157645380087391;
"needs_interstitial" = 0;
photos = 1;
primary = 14514940751;
secret = ebc107d841;
server = 5237;
title = {
"_text" = banjara;
};
videos = 0;
"visibility_can_see_set" = 1;
},
{
"_text" = "\n\t\t\n\t\t\n\t";
"can_comment" = 1;
"count_comments" = 0;
"count_views" = 0;
"date_create" = 1403849913;
"date_update" = 0;
description = {
"_text" = "Uploaded from my iPhone/iPod Touch";
};
farm = 4;
id = 72157645380777662;
"needs_interstitial" = 0;
photos = 1;
primary = 14516264624;
secret = 70097bb15c;
server = 3867;
title = {
"_text" = iuggjkd;
};
videos = 0;
"visibility_can_see_set" = 1;
}
);
};
I am stuck in this for hours.Can u suggest me how to deal with this.
Thanks for the reply
Try doing something like this. This is not the exact solution and you'll have to work around your way.
NSString *link = [NSString stringWithFormat:#"yourServiceURL"];
NSString *encdLink = [link stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:encdLink];
NSData *response = [NSData dataWithContentsOfURL:url];
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:response options: NSJSONReadingMutableContainers error: &error];
Now you have your data in the array and extract it out using objectForKey or valueForKey.You can use NSDictionary or NSArray as per your requirement.
This is what I am doing to fetch images from JSON and showing in my app. Firstly get the array from the above code. Then extract out the image content like this :
_demoArray = [json valueForKey:#"yourKeyField"];
Now you have the values in your demoArray.
Hope this helps.

Getting data from NSDictinionary [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I'm trying to get the "firstName" , "lastName" , "gender", "homeCity" and "email" from a NSDictionary
but It doesn't work...I have tried the following code:
NSDictionary *userInfo = [fsUser getUserInfo:#"self"];
NSLog(#"userInfo: %#", userInfo);
NSLog(#"name: %#", [userInfo objectForKey:#"firstName"]);
NSLog(#"lastName: %#", [userInfo objectForKey:#"lastName"]);
NSLog(#"gender: %#", [userInfo objectForKey:#"gender"]);
NSLog(#"homeCity: %#", [userInfo objectForKey:#"homeCity"]);
NSLog(#"email: %#", [userInfo objectForKey:#"email"]);
here is my dictionary value...
userInfo: {
userDictionary = {
meta = {
code = 200;
errorDetail = "Please provide an API version to avoid future errors.See http://bit.ly/vywCav";
errorType = deprecated;
};
notifications = (
{
item = {
unreadCount = 0;
};
type = notificationTray;
}
);
response = {
user = {
badges = {
count = 0;
items = (
);
};
bio = "";
checkinPings = off;
checkins = {
count = 0;
};
contact = {
email = "email#email.com";
};
firstName = Name;
following = {
count = 0;
};
friends = {
count = 0;
groups = (
{
count = 0;
items = (
);
name = "Amigos em comum";
type = friends;
},
{
count = 0;
items = (
);
name = "Outros amigos";
type = others;
}
);
};
gender = male;
homeCity = "";
id = 3233312;
lastName = lastName;
lists = {
groups = (
{
count = 1;
items = (
);
type = created;
}
);
};
mayorships = {
count = 0;
items = (
);
};
photo = "https://foursquare.com/img/blank_boy.png";
photos = {
count = 0;
items = (
);
};
pings = 0;
referralId = "u-sdsad";
relationship = self;
requests = {
count = 0;
};
scores = {
checkinsCount = 0;
goal = 50;
max = 0;
recent = 0;
};
tips = {
count = 0;
};
todos = {
count = 0;
};
type = user;
};
};
};
}
Use [userInfo objectForKey:#"userDictionary"] objectForKey:#"response"] objectForKey:#"user"] objectForKey:#"homeCity"].
This is where key-value coding (KVC) comes in handy. You can do (note use of valueForKey::
NSDictionary *userInfo = [fsUser getUserInfo:#"self"];
NSLog(#"userInfo: %#", userInfo);
NSLog(#"name: %#", [userInfo valueForKey:#"response.user.firstName"]);
NSLog(#"lastName: %#", [userInfo valueForKey:#"response.user.lastName"]);
NSLog(#"gender: %#", [userInfo valueForKey:#"response.user.gender"]);
NSLog(#"homeCity: %#", [userInfo valueForKey:#"response.user.homeCity"]);
NSLog(#"email: %#", [userInfo valueForKey:#"response.user.email"]);
But this isn't very efficient since you keep digging deep into the same dictionary. It would be better to do this:
NSDictionary *userInfo = [fsUser getUserInfo:#"self"];
NSDictionary *user = [userInfo valueForKey:#"response.user"];
NSLog(#"userInfo: %#", userInfo);
NSLog(#"name: %#", [user objectForKey:#"firstName"]);
NSLog(#"lastName: %#", [user objectForKey:#"lastName"]);
NSLog(#"gender: %#", [user objectForKey:#"gender"]);
NSLog(#"homeCity: %#", [user objectForKey:#"homeCity"]);
NSLog(#"email: %#", [user objectForKey:#"email"]);
It doesn't work because your userInfo doesn't have such keys.
userInfo has userDictionary, which has meta, notifications and response.
response has user, and user has firstName, lastName etc.
Your top leve is userInfo, but there are "objects" within that as well. You will have to traverse those to get to first name. Something like this will work:
NSLog(#"first name = %#", userInfo[#"userInfo"][#"userDictionary"][#"response"][#"user"][#"firstName"]);

iOS - File Input - Variable Typecasting Issues

Inputing a JSON file into Core Data using the following code I found on cimgf.com:
NSString *filePathGPS = [[NSBundle mainBundle] pathForResource:#"gps_6kb" ofType:#"json"];
if (filePathGPS) {
NSString *contentOfFile = [NSString stringWithContentsOfFile:filePathGPS encoding:NSUTF8StringEncoding error:nil];
NSDictionary *jsonDict = [contentOfFile objectFromJSONString];
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *areaName = [NSEntityDescription
insertNewObjectForEntityForName:#"Area"
inManagedObjectContext:context];
NSDictionary *attributes = [[areaName entity] attributesByName];
for (NSString *attribute in attributes) {
for (NSDictionary * tempDict in jsonDict) {
NSLog(#"Attribute = %#", attribute);
id value = [tempDict objectForKey:attribute];
NSLog(#"Value = %#", value);
if (value == nil) {
continue;
}
[areaName setValue:value forKey:attribute];
}
}
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
}
I get the following error:
2013-01-12 12:11:09.548 SuperGatherData[1194:707] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "area2"; desired type = NSString; given type = NSNull; value = <null>.'
I get why the error is occurring, because some of the values in the file are null and not strings. Here's a sample of the JSON data:
{
"area1": "International",
"area2": null,
"area3": null,
"area4": null,
"area5": null,
"latitude": "-25.2447",
"longtitude": "133.9453",
},
{
"area1": "Alaska",
"area2": "Anchorage & South Central Alaska ",
"area3": null,
"area4": null,
"area5": null,
"latitude": "61.2134",
"longtitude": "-149.8672",
},
{
"area1": "Alabama",
"area2": null,
"area3": null,
"area4": null,
"area5": null,
"latitude": "34.4112",
"longtitude": "-85.5737",
},
and realize I need to do something with the typecasting of attribute in the following line:
for (NSString *attribute in attributes) {
I just have no idea what that fix is. I'm new to Objective-C and haven't dealt with strongly typed languages before.
if (value == nil) should be if ([value isEqual:[NSNull null]]) instead - most JSON parsers represent an explicit null value by NSNull, since one can't store nil in an NSDictionary nor in an NSArray.

Resources