SAI RAM SAI RAM - 3 months ago 19
iOS Question

I want to move to another view controller after a dispatch_async task

I am trying to call a method from another view controller by creating an object in the present view controller. I am using dispatch_async block to do that with a serial queue.The next task of the serial queue must be the navigation to another controller (By the way it is the same controller I used the first task method from). But the serial queue is executing 2nd task even before fetching the data from 1st task. So the condition in the 2nd task fails and navigation won't happen. Please help me.

I saw many answers to use serial queue to get the job done but I know that to change user interface we have to be on main thread. So, is that why controller doesn't change? is there a way to create a serial queue on main thread? Or is it always on different thread? Any other solution to my problem is appreciated.

Here is my code:

dispatch_queue_t serialQueue=dispatch_queue_create("***", DISPATCH_QUEUE_SERIAL);

dispatch_async(serialQueue, ^
{
NSLog(@"first async");
[discoveryNewsObject callDiscoveryNewsRequest];
NSLog(@"first async complete");
});

dispatch_async(serialQueue(), ^
{
NSLog(@"second async");
if ([NSArray arrayWithArray:appDelegate.getNewsArray[0]].count==[NSArray arrayWithArray:appDelegate.postImageDimensionsArray].count && [NSArray arrayWithArray:appDelegate.getNewsArray[0]].count!=0)
{
NSLog(@"counts are equal");

[self performSegueWithIdentifier:@"DiscoverySegue" sender:self];
}
NSLog(@"second async complete");
});

Answer

you need to wait for both block completed after that you want to perform segue

try this code

  dispatch_group_t group = dispatch_group_create();

    dispatch_group_enter(group);
    dispatch_async(serialQueue, ^
                   {
                       NSLog(@"first async");
                       [discoveryNewsObject callDiscoveryNewsRequest];
                       NSLog(@"first async complete");
                       dispatch_group_leave(group);
                   });
    dispatch_group_enter(group);

    dispatch_async(serialQueue(), ^
                   {
                       NSLog(@"second async");
                       if ([NSArray arrayWithArray:appDelegate.getNewsArray[0]].count==[NSArray arrayWithArray:appDelegate.postImageDimensionsArray].count && [NSArray arrayWithArray:appDelegate.getNewsArray[0]].count!=0)
                       {
                           NSLog(@"counts are equal");

                       }
                       NSLog(@"second async complete");
                       dispatch_group_leave(group);

                   });

    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [self performSegueWithIdentifier:@"DiscoverySegue" sender:self];

    })
Comments