你创建你的解析器,但你不解析。假设您像这样创建了解析器:
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:URL];
然后您需要设置委托并启动解析:
parser.delegate = self;
[parser parse];
然后你必须编写你的NSXMLParserDelegate
方法。(有关 的更多信息NSXMLParser
,请参阅Event-Driven XML Programming Guide。)例如,如果您只需要温度,您可以编写一个didStartElement
方法:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:@"yweather:condition"])
{
// do whatever you want with `attributeDict`, perhaps saving it in some class property; I'm just going to log it
NSLog(@"current condition = %@", attributeDict);
}
}
注意,城市应该是WOEID。(请参阅API 描述。)因此,而不是以下位置:
NSString *location = @"Palermo";
您应该使用(对于意大利的巴勒莫):
NSString *location = @"719846";
顺便说一句,我同意 Caleb 的观点,即您应该initWithContentsOfURL
在后台队列中执行此操作,或者您应该NSData
使用一些异步机制来检索。
例如,您可以这样做:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *location = @"719846";
NSString *temperatureUnit = @"c";
NSString *address = @"http://weather.yahooapis.com/forecastrss?w=";
NSString *request = [NSString stringWithFormat:@"%@%@&u=%@",address,location, temperatureUnit];
NSURL *URL = [NSURL URLWithString:request];
NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:URL];
parser.delegate = self;
[parser parse];
});
如果您在后台队列中执行此操作,请确保将 UI 更新分派回主队列,例如:
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:@"yweather:condition"])
{
// UI updates should be dispatched back to the main queue, e.g.:
dispatch_async(dispatch_get_main_queue(), ^{
NSString *temp = attributeDict[@"temp"];
self.tempLabel.text = temp;
});
}
}