【问题标题】:Wait for Asynchronous request before execution of other code在执行其他代码之前等待异步请求
【发布时间】:2021-02-16 21:31:20
【问题描述】:

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

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

任何建议都会有所帮助。

【问题讨论】:

    标签: ios xcode8 nsurlsessiondownloadtask


    【解决方案1】:

    使用主线程更新异步代码内的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
        });
    }
    

    【讨论】:

    • 但是如果一开始没有进入else块代码,然后UILabel在this之后执行if(![self connected]) { NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; arrMyres = [[NSMutableArray alloc] initWithArray:[prefs objectForKey:@"Myres"]];在这种情况下,在异步块中移动 UILabel 更新代码将不起作用
    • 服务调用前,将第一个标签文本设置为空或加载文本,从api获得响应后,显示结果文本。如果 arrMyres.count 为 0,则显示未找到记录文本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    • 1970-01-01
    • 2020-06-20
    相关资源
    最近更新 更多