不過上次的方法有一個壞處,
就是用戶再開啟App,App是不會更新畫面,
只會出Default Image要直到Callback完成,
所以今天看了一下Help Document,
終於找到最好的方法了
UIBackgroundTaskIdentifier bgTask;
if(bgTask == UIBackgroundTaskInvalid)
{
UIApplication* app = [UIApplication sharedApplication];
// 開啟了BackgroundTask就要以令以下的queue在Background/Foreground Task都可以運行
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"System Expiration End Background Task");
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Do the work associated with the task.
for (int i = 0; i < 1000; i++)
{
NSLog(@"Sleep %d", i);
// 返回Main Process更新UI
dispatch_async(dispatch_get_main_queue(), ^{
UIButton* btn = (UIButton*)[viewController.view viewWithTag:100];
[btn setTitle:[NSString stringWithFormat:@"Sleep %d", i] forState:UIControlStateNormal];
});
[NSThread sleepForTimeInterval:5];
}
NSLog(@"Completed State End Background Task");
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
});
}
if(bgTask == UIBackgroundTaskInvalid)
{
UIApplication* app = [UIApplication sharedApplication];
// 開啟了BackgroundTask就要以令以下的queue在Background/Foreground Task都可以運行
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"System Expiration End Background Task");
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Do the work associated with the task.
for (int i = 0; i < 1000; i++)
{
NSLog(@"Sleep %d", i);
// 返回Main Process更新UI
dispatch_async(dispatch_get_main_queue(), ^{
UIButton* btn = (UIButton*)[viewController.view viewWithTag:100];
[btn setTitle:[NSString stringWithFormat:@"Sleep %d", i] forState:UIControlStateNormal];
});
[NSThread sleepForTimeInterval:5];
}
NSLog(@"Completed State End Background Task");
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
});
}
沒有留言:
張貼留言