ios - 了解后台任务执行语法和 GCD

标签 ios objective-c uikit grand-central-dispatch background-process

在研究 iOS 中的后台任务后,我试图完全理解我放在一起的以下代码,希望能得到一些帮助,

我理解基本概念,

首先我们获取应用程序单例,然后我们创建一个 block 并向系统注册后台任务,最后我们异步调度任务运行。

下面是我正在寻求帮助的部分:

  1. 当 background_task 被分配 block 时,实际 block 中没有我们想要运行的代码,只有完成处理程序中的清理代码,这是为什么?

  2. 我理解 dispatch_async 基本上启动了一个新线程并开始处理 block 中的代码,但是在这个 dispatch_async 请求中哪里引用了 background_task?我看不出系统是怎么理解我们在dispatch_async请求中要执行的代码是和我们之前注册的background_task相关的。

  3. 为什么我们需要在 dispatch_async block 的末尾 和 background_task 的完成处理程序中 清理代码?

对不起,如果这些是愚蠢的问题,但我只是不明白语法,

这是我拼凑的代码:

UIApplication *application = [UIApplication sharedApplication]; //Get the shared application instance

__block UIBackgroundTaskIdentifier background_task; //Create a task object

background_task = [application beginBackgroundTaskWithExpirationHandler: ^ { //Register background_task    
                [application endBackgroundTask: background_task]; //Tell the system that we are done with the tasks
                background_task = UIBackgroundTaskInvalid; //Set the task to be invalid
                //Above code called when endBackgroundTask is called
            }];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                //Perform your tasks that your application requires

                [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateText) userInfo:nil repeats:YES];
                NSLog(@"\n\nRunning in the background!\n\n");

                [application endBackgroundTask: background_task]; //End the task so the system knows that you are done with what you need to perform
                background_task = UIBackgroundTaskInvalid; //Invalidate the background_task
            });

最佳答案

后台任务标识符与您在辅助线程上所做的工作之间没有任何关系。后台任务表示请求一些额外的时间来运行。就这样。你需要结束它来告诉操作系统你已经完成了你想做的工作。如果您未能在可用时间内完成此操作,您的应用程序将被终止。任务 ID 只是一个 token ,表示操作系统允许继续工作一段时间。

您必须清理两个地方,过期处理程序和异步分派(dispatch) block 的末尾,因为它们代表两个不同的事件。在您分派(dispatch)到并发队列的 block 中,您结束了任务,因为您已经及时完成了工作,并且您想让操作系统知道,以便它可以暂停您的应用程序;它不需要终止它。在到期处理程序中,这是您结束任务以防止您的应用程序被终止的最后机会。你还没有完成你的工作,但你已经没时间了。如果您此时没有结束后台任务,操作系统会终止您的应用。

顺便说一句,在调度队列上运行的任务中调度计时器是行不通的。定时器被安排在线程的运行循环上。服务调度队列的工作线程可以随时终止,并且在任何情况下都不会运行它们的运行循环。

关于ios - 了解后台任务执行语法和 GCD,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20160923/

相关文章:

ios - UIWebView 显示没有内容的黑屏

ios - AUGraphAddNode -10862

function - SKScene 的更新 UIKit 等效

iphone - 允许 View 完全重绘,然后在主线程上执行操作

ios - swift 在 UITableViewCell 中播放多个视频依赖于 Scroll

iphone - 如何对 iphone 通讯录进行排序?

ios - Objective-C 中反斜杠 (\) 字符的使用

uikit - 自 Xcode 5.1 以来无法在 cocoapods 中构建模块 'UIKit"

ios - Swift - 带循环的多个链 http 请求

ios - Apple设备中的Google Analytics(分析)跟踪问题