看一下我的代碼,從網站服務器獲得數據,但是崩潰了:
- (void)loadDataSource
{
// Request
NSString *URLPath = [NSString stringWithFormat:@"http://imgur.com/gallery.json"];
NSURL *URL = [NSURL URLWithString:URLPath];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
**CRASHED HERE** [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
if (!error && responseCode == 200) {
id res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
if (res && [res isKindOfClass:[NSDictionary class]]) {
self.items = [res objectForKey:@"gallery"];
[self dataSourceDidLoad];
} else {
[self dataSourceDidError];
}
} else {
[self dataSourceDidError];
}
}];
}
代碼沒問題,但是結果中沒有對象關鍵字“gallery”的,看起來關鍵字好像是“data”。所以用下面的代碼:
self.items = [res objectForKey:@"data"]