gpt4 book ai didi

ios - 如何在 Objective-C 中异步获取 API 数据?

转载 作者:行者123 更新时间:2023-11-28 21:19:07 25 4
gpt4 key购买 nike

我所有的工作都很顺利,但是有一点问题。我在 -(void)viewDidLoad{} 中有我的 NSURLRequest,它花了一些时间从服务器获取数据。我希望它以异步方式完成。

以下是我的代码,请建议我应该实现什么。?在此先感谢大家。 :)

- (void)viewDidLoad {
[super viewDidLoad];
[[self tableView2]setDelegate:self ];
[[self tableView2]setDataSource:self];
array=[[NSMutableArray alloc]init];

NSString *castString = [NSString stringWithFormat:@"https://api.themoviedb.org/3/movie/%@/credits?api_key=c4bd81709e87b12e6c74a08609433c49",movieIDinString];
NSURL *url=[NSURL URLWithString:castString];

NSURLRequest *request=[NSURLRequest requestWithURL:url];
connection=[NSURLConnection connectionWithRequest:request delegate:self];
if (connection)
{
webData= [[NSMutableData alloc]init];
}

最佳答案

试试这个..

  dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Thread

NSString *castString = [NSString stringWithFormat:@"https://api.themoviedb.org/3/movie/%@/credits?api_key=c4bd81709e87b12e6c74a08609433c49",movieIDinString];
NSURL *url=[NSURL URLWithString:castString];

NSURLRequest *request=[NSURLRequest requestWithURL:url];
connection=[NSURLConnection connectionWithRequest:request delegate:self];
if (connection)
{
webData= [[NSMutableData alloc]init];
}

dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates

// reload table view here
[_activityIndicatorImageView stopAnimating];
});
});

关于ios - 如何在 Objective-C 中异步获取 API 数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40546696/

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