IOS Objective-C awaits asynchronous process

I call the code below from 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;
}

In the [self processAll] call, code is run with asynchronous calls, etc., and it will continue to cycle until all actions are completed, re-calling itself. When all tasks are completed, fetchComplete will be set to true. This part works great.

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

The problem is, quite rightly, the current check, while it works to show NSLogs, etc., is useless for returning BOOL back to the caller, since the process is currently async. I installed it for async so that it runs, otherwise I found that the processAll code is blocked from starting.

- , fetchComplete, , , bool ?

async , , - .

.

+4
3

. -, ,

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

fetchComplete true, ,

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

, fetchDidComplete, . .

[[NSNotificationCenter defaultCenter] removeObserver:self
                                                name:@"fetchDidComplete"
                                              object:nil];
+5

. . .

API.

  • , .
  • , .

, API async , , . , , while(!fetchComplete). .

+6

, , .

, , blocks notifications.

, function .

, asyc, AyncProcessor.

AyncProcessor * processor = [AyncProcessor sharedProcessor];
processor.delegate = self;
[processor start];

- . , , , .

//protocol method
-(void) processingComplete;

// and at some point in AsyncProcessor
[self.delegate processingComplete] 

AyncProcessor * processor = [AyncProcessor sharedProcessor];
[processor start:^()/{
  ///code in this block will complete after processing has completed
 }];

, NSNotification.

, , .

+1

Source: https://habr.com/ru/post/1539116/


All Articles