我在 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;
}
对 [self processAll] 的调用运行具有异步调用等的代码,并将一直循环直到所有事件完成,重复调用自身。所有任务完成后,fetchComplete 设置为 true。这部分工作正常。
我需要代码等待 fetchComplete 为真,然后返回一个 bool 值给 AppDelegate。
问题是,当前的检查虽然可以显示 NSLogs 等,但对于将 BOOL 返回给调用者毫无用处,因为该进程当前是异步的。我已将它设置为异步以便它运行,否则,我发现 processAll 代码被阻止运行。
有人可以阐明我如何监控 fetchComplete,并且只有在监控为真时才将 bool 返回给调用函数吗?
在 while 返回后,我尝试将 return 移到异步 block 中,但由于在 block 内调用,这会返回语法错误。
最佳答案
使用通知。首先,你必须像这样开始收听通知
[[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];
关于iOS Objective-C 等待异步进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23447325/