我所有的工作都很順利,但有一點問題。我在 - (void)viewDidLoad {}中有NSURLRequest,並且需要一些時間從服務器獲取數據。我希望它以異步的方式完成。如何在Objective-C中異步獲取API數據?
以下是我的代碼,請告訴我該怎麼實現。 在此向各位致謝。 :)
- (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),^(空隙){// 後臺線程 dispatch_async(dispatch_get_main_queue(),^(無效){// 運行UI更新 [_activityIndicatorImageView stopAnimating]; }); }); –
@SudheerKolasani請你解釋一下,因爲我是Objective-C –
的新手,它很簡單,只需在後臺加載url並在主線程中重新加載tableview –