ios - 在执行其他代码之前等待异步请求
问题描述
我正在使用[NSURLSession sharedSession] dataTaskWithRequest
从网络服务器获取数据并将其显示在标签中并根据它设置按钮图像但我的问题是首先执行标签代码并将它们显示为空然后异步块代码完成。
if(![self connected])
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
arrMyres = [[NSMutableArray alloc] initWithArray:[prefs objectForKey:@"Myres"]];
}
else
{
// POSTrequest with URL to get data from server
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:
^(NSData * _Nullable responseData,
NSURLResponse * _Nullable urlResponse,
NSError * _Nullable error) {
if (error) {
//Display error
}
else
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)urlResponse;
if([httpResponse statusCode ]>=200 && [httpResponse statusCode]<300)
{
dispatch_async(dispatch_get_main_queue(), ^{
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
NSArray *array=[[dataDictionary objectForKey:@"GetExistingFavorites"] isKindOfClass:[NSNull class]]? nil:[dataDictionary objectForKey:@"GetExistingFavorites"];
arrMyres=[[NSMutableArray alloc]initWithArray:array];
});
}
}
}] resume];
}
//This block of code executes first and displays empty label
if([arrMyres count]>0 )
{
//Set Button Image and display label
}
else
{
// Do something else
}
如何等待异步请求完成执行并在它之后的某个地方使用它?在研究过程中,我发现了调度组和完成处理程序。但无法理解如何实施
任何的意见都将会有帮助。
解决方案
使用主线程更新firstLabel
异步代码内的 UI 代码。参考下面的代码
if(![self connected])
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
arrMyres = [[NSMutableArray alloc] initWithArray:[prefs objectForKey:@"Myres"]];
[self updateUI];
}
else
{
// POSTrequest with URL to get data from server
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:
^(NSData * _Nullable responseData,
NSURLResponse * _Nullable urlResponse,
NSError * _Nullable error) {
if (error) {
//Display error
}
else
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)urlResponse;
if([httpResponse statusCode ]>=200 && [httpResponse statusCode]<300)
{
dispatch_async(dispatch_get_main_queue(), ^{
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
NSArray *array=[[dataDictionary objectForKey:@"GetExistingFavorites"] isKindOfClass:[NSNull class]]? nil:[dataDictionary objectForKey:@"GetExistingFavorites"];
arrMyres=[[NSMutableArray alloc]initWithArray:array];
//This block of code executes first and displays empty label
if([arrMyres count]>0 )
{
[self updateUI];
}
}
}
}] resume];
}
-(void)updateUI {
dispatch_async(dispatch_get_main_queue(), ^{
//update UI in main thread.
//Add your ui updates
});
}
推荐阅读
- flutter - 如何在 Flutter 或 Dart 中将字符串编码为 RFC 3986?
- c++ - 当对象很大时返回一个指针或值
- azure-devops - AzureDevOps:授予对组织中所有存储库的只读访问权限
- asp.net-core - .net 4.6 web api2 401 未经授权使用身份服务器 4
- ios - 在 Realm Swift 中使用时间戳值(Double 数据类型)作为主键
- python - 创建 Tensorflow 模型,该模型接受张量图像作为模型的输入
- php - 如何对具有对象外键值的数组进行排序必须是第一个(Laravel)
- javascript - 如何在动态创建的单选按钮上触发功能
- pandas - 跨两个轴的小计和总计
- r - R DataTable 选择行