首页 > 解决方案 > 在执行其他代码之前等待异步请求

问题描述

我正在使用[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
    } 

如何等待异步请求完成执行并在它之后的某个地方使用它?在研究过程中,我发现了调度组和完成处理程序。但无法理解如何实施

任何的意见都将会有帮助。

标签: iosxcode8nsurlsessiondownloadtask

解决方案


使用主线程更新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
    });
}

推荐阅读