我创建了一个使用 AFNetworking 并从 URL 获取 JSON 的方法。但我不知道如何在 ViewDidLoad 中使用它。我得到一个错误或一个空的 UITable。
这是我的代码:
@interface QWViewController ()
-(void)loadVideoFromURL:(NSURL *)url;
@end
@interface NSURL()
-(void)loadVideoFromURL:(NSURL *)url;
@end
// 我创建的方法:
-(void)loadVideoFromURL:(NSURL *)url {
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// setup AFNetworking stuff
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
// call delegate or processing method on success
self.myJSON = (NSDictionary *)JSON;
NSLog(@" json %@", self.myJSON);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
}];
[operation start];
}
// 这里是 ViewWillAppear:
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
//[super viewDidLoad];
NSLog(@" video Meta Data %@", self.myJSON);
// link to the youtube channel or playlist NOTE: JSON and JSONC are not the same. Use JSONC, as far as i recall, its customised for youtube.
NSString *urlAsString = @"http://gdata.youtube.com/feeds/api/playlists/PL7CF5B0AC3B1EB1D5?v=2&alt=jsonc&max-results=50";
NSURL *myurl = [NSURL URLWithString:urlAsString];
self.myJSON = [self loadVideoFromURL:myurl];
// I am using self.videoMetaData. I am defining it in the .h file as a property. This will let me use it anywhere in this .m file.
self.videoMetaData = [self.myJSON valueForKeyPath:@"data.items.video"];
NSLog(@" JSON view will apear %@", self.myJSON);
// This will have all the sq and hq thumbnails
// self.allThumbnails = [urlcontent valueForKeyPath:@"data.items.video.thumbnail"];
// The table need to be reloaded or else we will get an empty table.
[self.tableView reloadData]; // Must Reload
// NSLog(@" video Meta Data %@", self.videoMetaData);
}