gpt4 book ai didi

ios - 更新 block 内的 UI

转载 作者:行者123 更新时间:2023-11-29 11:46:34 26 4
gpt4 key购买 nike

我调用 youtube API 来获取视频的标题。然后我想在表格中的屏幕上显示视频的标题。 block 执行完毕后,如何访问 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"];
}];

block 执行完毕后如何访问 block 外的title变量?

我尝试了以下但没有成功

    dispatch_async(dispatch_get_main_queue(), ^{
[self updateMyUserInterfaceOrSomething];
});

最佳答案

在您的代码中:

    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
}

关于ios - 更新 block 内的 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43491828/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com