Passing Array to UIWebView - ios

I currently am pulling directions from google and storing them into an array. I then have an integer for the amount of directions found, and have the forloop displaying them via NSLog properly (with the html included)
My question is, how do I make this into a UIWebView so that it properly displays this information in a list?
Here is my code so far:
NSError *error;
NSString *currentLoc = #"Hyannis, MA";
NSString *directionsString = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%#&destination=%#, %#, %#&sensor=false", currentLoc, [self.selectedEvent objectForKey:#"eventAddress"], [self.selectedEvent objectForKey:#"eventCity"], [self.selectedEvent objectForKey:#"eventState"]];
directionsString = [directionsString stringByReplacingOccurrencesOfString:#" " withString:#"+"];
NSData *jsonResponse = [NSData dataWithContentsOfURL:[NSURL URLWithString:directionsString]];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonResponse options:kNilOptions error:&error];
self.directionsArray = [[[[jsonDict valueForKey:#"routes"] valueForKey:#"legs"] valueForKey:#"steps"] valueForKey:#"html_instructions"];
NSUInteger total = [self.directionsArray count];
for (int i = 0; i < total; i++)
{
NSString *statusString = [jsonDict valueForKey:#"status"];
NSLog(#"JSON Response Status:%#", statusString);
NSLog(#"Direction: %#", [self.directionsArray objectAtIndex:i]);
}

Related

How to print the json data

I'm trying to learn JSON with IOS since I'm a beginner in IOS devices, i tried this code so far
-(void)retriveData
{
NSURL *url = [NSURL URLWithString:#"http://localhost/testjson.php"];
NSData *data = [NSData dataWithContentsOfURL:url];
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
cities = [[NSMutableArray alloc] init];
for (int i=0; i<json.count; i++) {
NSString *cID = [[json objectAtIndex:i] objectForKey:#"id"];
NSString *cName = [[json objectAtIndex:i] objectForKey:#"CityName"];
NSString *cState = [[json objectAtIndex:i] objectForKey:#"CityState"];
NSString *cPopulation = [[json objectAtIndex:i] objectForKey:#"CityPopulation"];
NSString *cCountry = [[json objectAtIndex:i] objectForKey:#"Country"];
Country *myCity = [[Country alloc] initWithCityID:cID andCityName:cName andCityState:cState andCityPopulation:cPopulation andCityCountry:cCountry];
[cities addObject:myCity];
}
}
Anyone can show me now how i can print the data? this is the json file
[{"0":"1","id":"1","1":"Muscat","CityName":"Muscat","2":"Muscat","CityState":"Muscat","3":"25000","CityPopulation":"25000","4":"Oman","Country":"Oman"},{"0":"2","id":"2","1":"Bawsher","CityName":"Bawsher","2":"Muscat","CityState":"Muscat","3":"10000","CityPopulation":"10000","4":"Oman","Country":"Oman"},{"0":"3","id":"3","1":"AlMawalih","CityName":"AlMawalih","2":"Seeb","CityState":"Seeb","3":"5000","CityPopulation":"5000","4":"Oman","Country":"Oman"},{"0":"4","id":"4","1":"Oran","CityName":"Oran","2":"Oran","CityState":"Oran","3":"100000","CityPopulation":"100000","4":"Algeria","Country":"Algeria"},{"0":"5","id":"5","1":"Constantine","CityName":"Constantine","2":"Constantine","CityState":"Constantine","3":"150000","CityPopulation":"150000","4":"Algeria","Country":"Algeria"}]
Below is my very understandable and basic coding according to your question.It is helpful for you.
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://localhost/testjson.php"]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json;charset=UTF-8" forHTTPHeaderField:#"content-type"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//You need to check response.Once you get the response copy that and paste in ONLINE JSON VIEWER in GOOGLE.If you do this clearly you can get the correct results.
//After that it depends upon the json format whether it is DICTIONARY or ARRAY
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
NSLog(#"The json output array is - %#",jsonArray);
for(int i=0;i>[jsonArray count];i++)
{
NSString *strZero = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"0"]];
NSLog(#"The zero is-%#",strZero);
NSString *strOne = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"1"]];
NSLog(#"The One is-%#",strOne);
NSString *strTwo = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"2"]];
NSLog(#"The Two is-%#",strTwo);
NSString *strThree = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"3"]];
NSLog(#"The three is-%#",strThree);
NSString *strFour = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"4"]];
NSLog(#"The four is-%#",strFour);
NSString *strID = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"id"]];
NSLog(#"The ID is-%#",strID);
NSString *strCityName = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"CityName"]];
NSLog(#"The CityName is-%#",strCityName);
NSString *strCityState = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"CityState"]];
NSLog(#"The CityState is-%#",strCityState);
NSString *strCityPopulation = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"CityPopulation"]];
NSLog(#"The CityPopulation is-%#",strCityPopulation);
NSString *strCountry = [NSString stringWithFormat:#"%#",[array objectAtIndex:i]valueForKey:#"Country"]];
NSLog(#"The Country is-%#",strCountry);
}
By printing you mean show the data in the console ?
Did you try this ?
NSString* str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Data: %#", str);

json populate table view controller wont work

I've been following a tutorial on youtube on how to load external data from a database on to a iOS application. I understand the concept and how it works etc. But I'm having an error even though I'm following the video and from looking online it seems to be a common error.
- (void) retrieveData
{
NSURL * url = [NSURL URLWithString: getDataURL];
NSData * data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData: data options:kNilOptions error:nil];
//set up our cities array
citiesArray = [[NSMutableArray alloc] init];
// loop through our json array
for (int i =0; i< jsonArray.count; i++)
{
//create our city object
NSString * cID = [[jsonArray objectAtIndex:i] objectForKey:#"id"];
NSString * cName = [[jsonArray objectAtIndex:i] objectForKey:#"cityName"];
NSString * cState = [[jsonArray objectAtIndex:i] objectForKey:#"cityState"];
NSString * cPopulation = [[jsonArray objectAtIndex:i] objectForKey:#"cityPopulation"];
NSString * cCountry = [[jsonArray objectAtIndex:i] objectForKey:#"country"];
// Add the city object to our cities array
[citiesArray addObject:[[City alloc]initWithCityName:cName andCityState:cState andCityCountry:cCountry andCityPopulation:cPopulation andCityID:cID]];
}
//reload our table view
[self.tableView reloadData];
}
The code fails on the third line.
jsonArray = [NSJSONSerialization JSONObjectWithData: data options:kNilOptions error:nil];
Why is that? Any suggestions? The jsonArray has already been created, so I can't understand why it won't work.
I checked your code & i don't think there is any error.
I hope you've declared NSMutableArray *jsonArray in header (.h) file.
If you getting error in thos line :
jsonArray = [NSJSONSerialization JSONObjectWithData: data options:kNilOptions error:nil];
than replace kNilOptions with simply nil.
If you getting crash than it might be because nil data. In that case you have to put condition before you store data in array something like this :
if (data != nil)
{
jsonArray = [NSJSONSerialization JSONObjectWithData: data options:nil error:nil];}
Hope it'll help.

Unrecognized selector sent to instance in JSON parsing

Please help me debug this code
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSError *error = nil;
NSURL *urls = [NSURL URLWithString:[NSString stringWithFormat:#"http://cnapi.iconnectgroup.com/api/UserProfile?id=1"]];
NSString *json = [NSString stringWithContentsOfURL:urls encoding:NSASCIIStringEncoding error:&error];
NSLog(#"JSon data = %# and Error = %#", json, error);
if(!error)
{
NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];
NSArray *myJsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
NSLog(#"JSON data is :: %#", myJsonArray);
for(NSDictionary *jsonDictionary in myJsonArray)
{
//NSString *uids = jsonDictionary[#"UID"];
NSString *address1 = jsonDictionary[#"Address1"];
NSString *address2 = jsonDictionary[#"Address2"];
NSString *city = jsonDictionary[#"City"];
NSString *emailId = jsonDictionary[#"EmailID"];
NSString *fname = jsonDictionary[#"FName"];
NSString *fax = jsonDictionary[#"Fax"];
NSString *lname = jsonDictionary[#"LName"];
NSString *password = jsonDictionary[#"Password"];
NSString *phone = jsonDictionary[#"Phone"];
NSString *state = jsonDictionary[#"State"];
NSString *uids = [jsonDictionary objectForKey:#"UID"];
NSString *zip = jsonDictionary[#"Zip"];
NSString *company = jsonDictionary[#"company"];
NSString *department = jsonDictionary[#"department"];
NSLog(#"Uid is = %#", uids);
NSLog(#"First Name = %#", fname );
NSLog(#"Last Name = %#", lname);
NSLog(#"Company = %#", company);
NSLog(#"Email Id = %#", emailId);
NSLog(#"Password = %#", password);
NSLog(#"Department = %#", department);
NSLog(#"Address 1 = %#", address1);
NSLog(#"Address 2 = %#", address2);
NSLog(#"City = %#", city);
NSLog(#"State = %#", state);
NSLog(#"Zip = %#", zip);
NSLog(#"Phone = %#", phone);
NSLog(#"Fax = %#", fax);
}
}
});
[activity stopAnimating];
self.activity.hidden = YES;
}
Image will give you where the error is. I get this error after clicking stepover to debug. I also tried
NSString *address1 = [jsonDictionary objectForKey:#"Address1"];
From the output of url, it shows it's not array but a dictionary. You are trying to convert to array here.
NSArray *myJsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
instead use this
NSDictionary *myJsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
then remove that for loop no need of it. and replace your variable jsonDictionary with myJsonDictionary so to retrieve values.
// for(NSDictionary *jsonDictionary in myJsonArray)
Run now it will be fine. Worked for me fine
If the output was array of Dictionaries it would have been looked like this with square brackets around.
For Ex: [{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]
If you are not sure of nature of response from url you can check for
the type. For ex:
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
if ([jsonObject isKindOfClass:[NSArray class]]) {
NSLog(#"its an array!");
NSArray *myJsonArray = (NSArray *)jsonObject;
// Handle Array of Dictionary
for(NSDictionary *jsonDictionary in myJsonArray)
{
NSString *address1 = jsonDictionary[#"Address1"];
//and so on
}
}
else {
NSLog(#"It's Dictionary");
NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
NSLog(#"jsonDictionary - %#",jsonDictionary);
//Handle NSDictionary
}
jsonDictonary is a NSString not as you expect NSDictonary.
Double check your JSON and maybe before calling that function check if it's NSDictonary.
Your should use one of the semi-standard frameworks for parsing JSON into Core Data. There are some SO questions about those.
In this case, your JSON has only one object which is not an array.
In general, your app shouldn't abort if server sent something unexpected, so it's better to use a parser which will loudly complain about malformed JSON than with it from scratch.

JSON Geocoding for iOS - parse latitude/longitude to address

I am trying to create an autocomplete addresses suggestion using JSON.
The problem that I am facing is that I can get the latitude and longitude from a the user types on the UISearchDisplay. However I am trying to parse this data to addresses names. I was trying to use reverse geocoding from Apple but with no success. I am receiving only one value.
I was using apple geocoding straight away but the results were not what I was expecting.
Here is the code:
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
NSError *error;
NSString *lookUpString = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?address=%#&sensor=true", 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:#"geometry"] valueForKey:#"location"];
int total = self.locationArray.count;
for (int i = 0; i < total - 1; i++)
{
NSLog(#"locationArray count: %d", self.locationArray.count);
NSArray *localLocations;
localLocations = [self.locationArray objectAtIndex:i];
NSLog(#"%d",i);
NSString *latitudeString = [localLocations valueForKey:#"lat"];
NSString *longitudeString = [localLocations valueForKey:#"lng"];
NSLog(#"LatitudeString:%# & LongitudeString:%#", latitudeString, longitudeString);
NSString *statusString = [jsonDict valueForKey:#"status"];
NSLog(#"JSON Response Status:%#", statusString);
double latitude = 0.0;
double longitude = 0.0;
latitude = [latitudeString doubleValue];
longitude = [longitudeString doubleValue];
CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
[self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error){
[[self placemarks] addObject:placemarks];
NSLog(#"PLACEMARKS %d", self.placemarks.count);
}];
}
NSLog(#"Mutable array %d", self.placemarks.count);
[self.searchDisplayController.searchResultsTableView reloadData];
return NO;
}
The NSLog(#"PLACEMARKS %d", self.placemarks.count); only display once, in the end of the task.
Any suggestions?
I really was doing so much more than the necessary.
Here is my code now:
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
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:#"geometry"];
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]);
}
[self.searchDisplayController.searchResultsTableView reloadData];
return NO;
}

iOS JSON Parsing error

I am trying to parse a json here but keep on getting errors for some reason. my code is
NSString *string = [NSString stringWithFormat:#"http://api.wunderground.com/api/3c158b3b3cd6ce90/hourly/q/11758.json"];//, query];
NSString *string2 = [string stringByReplacingOccurrencesOfString:#" " withString:#"_"];
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString:string]];
NSError* error;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
NSArray* latestLoans = [res objectForKey:#"forecast"]; //2
NSArray *tmp = [latestLoans valueForKey:#"temp"];
NSLog(#"temp: %#", tmp);
and the error is
temp: (null)
Entity: line 2: parser error : Start tag expected, '<' not found
{
^
I don't get this because the URL is real and gets a response, and I need help with this
What you are looking for, "forecast", does not exist in the response. Perhaps what you are looking for is "hourly_forecast".
NSArray* latestLoans = [res objectForKey:#"hourly_forecast"]; //2
NSArray *tmp = [latestLoans valueForKey:#"temp"];

Resources