Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Objective-C wait for async process

I am calling the code below from within the AppDelegate:

-(void) application:(UIApplication *)application performFetchWithCompletionHandler:
(void (^)(UIBackgroundFetchResult))completionHandler {


-(BOOL)backgroundRefresh{
    newData = false;
    callStartTime = [NSDate date];

    [self processAll];
       dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        while(!fetchComplete);
        NSLog(@"NOW COMPLETE");

   });
    NSLog(@"Got here now!");
    return newData;
}

The call to [self processAll] runs code that has async calls etc, and will keep looping around until all activities are complete, repeatedly calling itself. Once all tasks are complete, fetchComplete is set to true. This part works fine.

I need the code to wait for fetchComplete to be true, and then return a bool back to AppDelegate.

The issue is, that quite rightly, the current checking, whilst it works to show the NSLogs etc., is of no use to returning the BOOL back to the caller, as the process is currently async. I have set it to async so that it runs, otherwise, I find that the processAll code is being blocked from running.

Could someone please shed some light onto how I can monitor for fetchComplete, and only once that is true return the bool to the calling function?

I have tried moving the return to into the async block, after the while has returned, but this returns a syntax error due to calling within the block.

like image 559
NeilMortonNet Avatar asked May 03 '14 16:05

NeilMortonNet


1 Answers

Use a notification. First, you must start listening to the notification like this

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(fetchDidComplete)
                                             name:@"fetchDidComplete"
                                           object:nil];

Where ever you set fetchComplete to true, post a notification like this

[[NSNotificationCenter defaultCenter] postNotificationName:@"fetchDidComplete"
                                                    object:self
                                                  userInfo:nil];

Then you should have a method called fetchDidComplete that will do the post completion work. Don't forget to stop listening to the notification once done.

[[NSNotificationCenter defaultCenter] removeObserver:self
                                                name:@"fetchDidComplete"
                                              object:nil];
like image 186
Zia Avatar answered Oct 04 '22 06:10

Zia