OGeek|极客世界-中国程序员成长平台

标题: ios - 苹果ios后台执行示例 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 15:38
标题: ios - 苹果ios后台执行示例

苹果给 this of background execution :

- (void)applicationDidEnterBackgroundUIApplication *)application
{
    bgTask = [application beginBackgroundTaskWithName"MyTask" 
    expirationHandler:^{
    // Clean up any unfinished task business by marking where you
    // stopped or ending the task outright.
    [application 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, preferably in chunks.

    [application endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
    });
}

这个示例对我来说从来没有多大意义,我已经看到它被复制到许多后台应用程序示例中。

首先没有意义的是expirationHandler中的这两行:

[application endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;

bgTask 在 block 中捕获时似乎没有值。编译器这样提示。然后在 dispatch_async 下面的示例中显示了相同的两行。我希望它在 dispatch_async 中,但不在 block 中。谁能解释为什么我们在 block 中有这些行?

beginBackgroundTaskWithName 的文档还说“标志着一个新的长期运行的后台任务的开始。”它究竟是如何做到的?什么定义了任务? block 范围内是否有任何代码?



Best Answer-推荐答案


bgTask = [application beginBackgroundTaskWithName"MyTask" expirationHandler:]

告诉 iOS 你的应用程序正在启动一个新的后台任务。 iOS 不关心哪个代码构成了任务,它只知道它需要给你的应用更多的时间在后台执行。

此行执行后,bgTask 将包含新的后台任务标识符。

当你的后台任务完成后,你调用 [application endBackgroundTask:bgTask]; 并且 iOS 知道你的应用已经完成了指定的后台任务并且可能不需要更多的后台执行时间(你可能还有其他由 beginBackgroundTaskWithName:expirationHandler 发起的后台任务未完成)。

行:

bgTask = UIBackgroundTaskInvalid;

只是做家务;如果您省略此行,则不会发生任何错误,但 bgTask 将包含无效标识符。

如果您在应用的后台时间到期之前未调用 endBackgroundTask,则将调用到期处理程序 block 。

在过期处理程序中,bgTask 将具有您调用 beginBackgroundTaskWithName:expirationHandler 时分配的值,因此这就是传递给 endBackgroundTask 的值> 再次分配 UIBackgroundTaskInvalid 只是做家务

关于ios - 苹果ios后台执行示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45851687/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4