Wait for Asynchronous request before execution of other code

30 Views Asked by At

I'am using [NSURLSession sharedSession] dataTaskWithRequest to get data from webserver and display it in a label & set button images according to it But my problem is first label code is executed and they are displayed as empty then async block code is finished.

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
    } 

How to wait for asynchrous request to complete execution and use it results somewhere after it? During research I found about dispatch groups and completion handlers. but couldnt understand how to implement

Any suggestions would be helpful.

1

There are 1 best solutions below

2
Prakash On

Update firstLabel UI code inside of async code using main thread. Refer below code

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
    });
}