我调用youtube API获取视频标题。然后,我想在表格中显示屏幕上的视频标题。在块执行完毕后如何访问title
?
以下是获取标题的代码
-(void)getVideoTitle:(NSString *)urlStr success:(void (^)(NSDictionary *responseDict))success{
urlStr = [NSString stringWithFormat:@"https://www.googleapis.com/youtube/v3/videos?part=contentDetails%%2C+snippet%%2C+statistics&id=%@&key={API_KEY}",urlStr];
NSURL *url = [[NSURL alloc] initWithString:urlStr];
// Create your request
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// Send the request asynchronously
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *connectionError) {
// Callback, parse the data and check for errors
if (data && !connectionError) {
NSError *jsonError;
NSDictionary *jsonResult = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];
if (!jsonError) {
success(jsonResult);
// NSLog(@"Response from YouTube: %@", jsonResult);
}
}
}] resume];
}
以下是我如何调用上述函数:
[self getVideoTitle:@"zB4I68XVPzQ" success:^(NSDictionary *responseDict){
NSArray *itemsArray = [responseDict valueForKey:@"items"];
NSDictionary *item = itemsArray[0];
NSDictionary* snippet = [item valueForKey:@"snippet"];
NSString *title = [snippet valueForKey:@"title"];
}];
如何在块执行完后访问块外的title
变量?
我试过以下但没有运气
dispatch_async(dispatch_get_main_queue(), ^{
[self updateMyUserInterfaceOrSomething];
});
答案 0 :(得分:1)
在您的代码中:
NSString* recievedTitle __block = nil; //title is here, after block below run
[self getVideoTitle:@"zB4I68XVPzQ" success:^(NSDictionary *responseDict){
NSArray *itemsArray = [responseDict valueForKey:@"items"];
NSDictionary *item = itemsArray[0];
NSDictionary* snippet = [item valueForKey:@"snippet"];
recievedTitle = [snippet valueForKey:@"title"]; //here you write it
// or
NSString *title = [snippet valueForKey:@"title"];
[self updateInterfaceWithTitle: title]
}];
///
- (void)updateInterfaceWithTitle:(NSString*)title{
//use title here
}