I am trying to get weather information for an iPhone application. If I enter a 5 digit zipcode, the code is working. However, I want to make sure that if the user does not enter a valid city or zip code, it doesnt crash. The problem is that with Google Weather API, the XML data reads "city 开发者_高级运维data" when a valid place is entered, and "problem_cause data" when it is not a valid place. Please help!
-(IBAction) getlocation {
NSString *locationentered = location.text;
if ([locationentered isEqualToString: @""]) {
locationlabel.text = @"Please Enter a Location";
}
else {
NSString * locationen = locationentered;
NSString * address = @"http://www.google.com/ig/api?weather=";
NSString * request = [NSString stringWithFormat:@"%@%@",address,locationen];
NSURL * URL = [NSURL URLWithString:request];
NSError * error;
NSString* XML = [NSString stringWithContentsOfURL:URL encoding:NSASCIIStringEncoding error:&error];
NSString * temptoday = [[[[XML componentsSeparatedByString:@"city data=\""] objectAtIndex:1] componentsSeparatedByString:@"\""] objectAtIndex:0];
NSString * errorlocation = [[[[XML componentsSeparatedByString:@"problem_cause data=\""] objectAtIndex:1] componentsSeparatedByString:@"\""] objectAtIndex:0];
if ([errorlocation isEqualToString: @""]) {
locationlabel.text = @"Invalid Location";
}
if ([temptoday isEqualToString:@"(null)"]) {
locationlabel.text = @"Location present";
}
else {
locationlabel.text = temptoday;
}
}
}
The result is XML so use an XMLParser to look at it. In this case the standard Cocoa one is NSXMLParser and then setup a delegate which will get called for each element.
For the start of an element you will get called parser:didStartElement:namespaceURI:qualifiedName:attributes:
and this will pass in the element name in this case problem_cause or forecast_information depending if the input was good.
See Apple's Event-Driven XML Programming Guide for more or look at DOM parsers from this Stack Exchange question
精彩评论