【问题标题】:UIApplication.shared.beginBackgroundTask is not working on iOS 13UIApplication.shared.beginBackgroundTask 不适用于 iOS 13
【发布时间】:2020-02-04 12:43:02
【问题描述】:

UIApplication.shared.beginBackgroundTask 在 iOS 13 上无法运行。是否有任何替代方法可以在 iOS 13 上实现长时间运行的后台任务?此外,它在 iOS 12 及以下版本上也能完美运行。

当应用程序进入后台时,它会在 2 分钟内终止,而我希望它在后台继续运行数小时,因为我们正在后台进行一些处理。

以下是我正在使用的代码,这样当我的应用程序处于后台时,它可以获得额外的执行时间。我们需要额外的执行时间,因为我们定期将当前位置发送到服务器。

/// Register background task. This method requests additional background execution time for the app
private func registerBackgroundTask() {
    DispatchQueue.global().async {
        self.backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "BgTask", expirationHandler: {
            // Ends long-running background task
            self.endBackgroundTask()
        })
    }
}

/// Ends long-running background task. Called when app comes to foreground from background
private func endBackgroundTask() {
    UIApplication.shared.endBackgroundTask(backgroundTask)
    backgroundTask = UIBackgroundTaskInvalid
}

【问题讨论】:

    标签: ios13 swift4.2


    【解决方案1】:

    它工作得很好。根据定义,它应该将您的应用程序的后台执行时间延长几分钟,以便您完成已经开始的任务,如果没有正确完成,这可能对您的应用程序有害。以前是10分钟,现在是3分钟。其实我认为是30秒,根据我在网上找到的最新文章来看

    因此,这绝对不是满足您需求的正确工具。尝试查看URLSessionConfiguration.background(withIdentifier:),但要小心,因为它存在许多风险和一些错误。

    此外,请在互联网上搜索 Dropbox 后台位置更新,了解 Dropbox 如何解决后台限制。

    祝你好运

    【讨论】:

    • 是的,是30秒,iOS 13有效。回复后台URLSessionConfiguration,当然,更复杂(你必须使用委托API,而不是完成处理程序API;你必须使用文件上传任务的 API;等等),但它不是错误的,恕我直言。这是一个非常强大且非常宝贵的工具。我在 S.O. 上看到的 99% 的后台 URL 会话“问题”是程序员错误的结果,而不是 API 本身的任何“错误”。
    【解决方案2】:

    有关 iOS 13 中后台任务的总法律顾问,请参阅 WWDC 2019 Advances in App Background Execution。但简短的回答是,您不能让应用程序无限期地在后台运行。 Apple 这样做是为了确保应用不会耗尽用户的电量。

    如果您想“定期将当前位置发送到服务器”,我建议您查看significant change location servicevisits location service。借助这些服务,如果用户位置发生重大变化,操作系统可以唤醒您的应用。

    也见Handling Location Events in the Background

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-05
      • 2020-02-09
      • 1970-01-01
      • 2021-06-09
      • 2019-11-13
      • 1970-01-01
      • 2020-06-09
      相关资源
      最近更新 更多