我正在尝试获取 iPhone 应用程序的天气信息。如果我输入 5 位数的邮政编码,则该代码有效。但是,我想确保如果用户没有输入有效的城市或邮政编码,它不会崩溃。问题在于,使用 Google Weather API 时,XML 数据在输入有效地点时读取“城市数据”,当输入无效地点时读取“problem_cause 数据”。请帮忙!
-(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;
}
}
}