我从 JSON(对 Web 服务完全陌生)开始,这样做是为了从 Wunderground API 收集数据。这个同步代码对我有用:
NSDictionary *weatherData;
NSString *urlString;
if (self.apiKey) {
urlString = [@"http://api.wunderground.com/api/" stringByAppendingString:self.apiKey];
}
urlString = [urlString stringByAppendingString:@"/conditions/q/CA/San_Francisco.json"];;
NSURL *url = [NSURL URLWithString:urlString];
NSData *jasonData = [NSData dataWithContentsOfURL:url];
NSError *error;
weatherData = [NSJSONSerialization JSONObjectWithData:jasonData options:0 error:&error];
if (error) {
NSLog(@"Error creating JSON Object, error description = %@", [error localizedDescription]);
}
return weatherData;
// returns a dictionary
但这不会:
__block NSDictionary *weatherData;
dispatch_queue_t weatherDataQueue = dispatch_queue_create("weatherDataQueue", NULL);
dispatch_async(weatherDataQueue, ^{
NSString *urlString;
if (self.apiKey) {
urlString = [@"http://api.wunderground.com/api/" stringByAppendingString:self.apiKey];
}
urlString = [urlString stringByAppendingString:@"/conditions/q/CA/San_Francisco.json"];;
NSURL *url = [NSURL URLWithString:urlString];
NSData *jasonData = [NSData dataWithContentsOfURL:url];
NSError *error;
weatherData = [NSJSONSerialization JSONObjectWithData:jasonData options:0 error:&error];
if (error) {
NSLog(@"Error with creating JSON Object, error description %@", [error localizedDescription]);
}
});
NSLog(@"weatherData = %@", weatherData);
return weatherData;
// returns NULL
现在,我意识到这可能与当我返回时weatherData
,分派块中的代码尚未运行这一事实有关。如果有人能帮我弄清楚如何解决这个问题,我将不胜感激。