GCD 和 UIBackgroundTaskIdentifier
我有一个调度队列,里面有一些工作。当应用程序进入后台时,我希望队列继续运行,直到时间耗尽或队列耗尽。我将如何设置 UIBackgroundTaskIdentifier?
我需要像这样将其放入调度块中吗?
dispatch_async(queue, ^{
if (_bgTask == UIBackgroundTaskInvalid) {
if ([UIDevice currentDevice].multitaskingSupported) {
_bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^(void) {
if (_bgTask != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:_bgTask];
_bgTask = UIBackgroundTaskInvalid;
}
}];
}
}
...
...
if (_bgTask != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:_bgTask];
_bgTask = UIBackgroundTaskInvalid;
}
});
我认为上面发生的情况是它没有注册为长时间运行的任务,直到队列实际运行该块。那么我是否需要将代码的后台部分放在块之外,以便它在实际排队之前执行?
I have a dispatch queue that has some work in it. I want the queue to keep running till either time runs out or the queue gets drained, when the application goes into the background. How would I set up the UIBackgroundTaskIdentifier?
Do I need to put it into the dispatch block like so?
dispatch_async(queue, ^{
if (_bgTask == UIBackgroundTaskInvalid) {
if ([UIDevice currentDevice].multitaskingSupported) {
_bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^(void) {
if (_bgTask != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:_bgTask];
_bgTask = UIBackgroundTaskInvalid;
}
}];
}
}
...
...
if (_bgTask != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:_bgTask];
_bgTask = UIBackgroundTaskInvalid;
}
});
I think what happens in the above is it isn't registered as a long running task till the queue actually runs the block. So do I need to place the backgrounding portion of the code outside the block, so that it executes prior to being actually queued up?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定你为什么要在我认为是 ivar 的情况下跟踪 UIBackgroundTaskID 。最简单的方法是:
I am not sure why you are keeping track of the
UIBackgroundTaskID
in what I assume is an ivar. The easiest way to do this is:如果您有一个包含工作项的调度队列,并且您进入后台,该队列将继续处理其任务 180 秒(iOS 7 及更高版本)。之后,操作系统会自动暂停一切。所以不再需要 NSThreads、NSTimers 甚至 NSOperationQueues。一切都暂停了。
所以我不确定您试图在应用程序层中添加哪些额外代码来实现您想要做的事情。它是预先构建的。
If you have a dispatch queue with work items in it and you go to background the queue will continue working on its tasks for 180 seconds (iOS 7 and above). After that everything is paused automatically by the OS. So no more NSThreads, NSTimers and even NSOperationQueues. Everything is paused.
So I am not sure what extra code you are trying to add in your application layer to achieve what you are trying to do. It comes pre-built.