定期在后台快速运行代码

标签 swift

即使在后台,我的 swift 应用程序也需要定期运行一段代码。实现该目标的最佳方法是什么? 我试过 DispatchQueue.global(qos: .background).async 但没用

新尝试:

我将其添加到我的 ViewController 中:

private var time: Date?
private lazy var dateFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.dateStyle = .short
    formatter.timeStyle = .long
    return formatter
}()

func fetch(_ completion: () -> Void) {
    time = Date()
    completion()
}

这是我的 AppDelegate

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
    // Override point for customization after application launch.
    return true
}

func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    if let tabBarController = window?.rootViewController as? UITabBarController,
        let viewControllers = tabBarController.viewControllers
    {
        for viewController in viewControllers {
            if let fetchViewController = viewController as? ViewController {
                fetchViewController.fetch {
                    completionHandler(.newData)
                    print("fired")
                }
            }
        }
    }
}

并在 completionHandler(.newData) 上放置一个断点。 但是当我运行应用程序时,断点永远不会被触发。打印语句从未执行。

最佳答案

iOS 不允许您的应用程序在后台运行时按您的意愿继续运行进程。当它第一次进入后台时,您将有很短的时间来执行一些任务(大约几分钟),然后它就会停止。

然后,您需要使用后台提取来定期为您的应用提取新信息。

在 Ray Wenderlich 网站上有一个关于 iOS 支持的各种背景模式的很好的教程:RayWenderlich - Background modes .

还有一个guide on Apples developer portal这解释了当应用程序处于后台时您可以做什么和不能做什么。

Implementing Long-Running Tasks

For tasks that require more execution time to implement, you must request specific permissions to run them in the background without their being suspended. In iOS, only specific app types are allowed to run in the background:

  • Apps that play audible content to the user while in the background, such as a music player app
  • Apps that record audio content while in the background
  • Apps that keep users informed of their location at all times, such as a navigation app
  • Apps that support Voice over Internet Protocol (VoIP)
  • Apps that need to download and process new content regularly
  • Apps that receive regular updates from external accessories
  • Apps that implement these services must declare the services they support and use system frameworks to implement the relevant aspects of those services.

Declaring the services lets the system know which services you use, but in some cases it is the system frameworks that actually prevent your application from being suspended.

更新:

首先,我不会将刷新代码放在 ViewController 中,VC 在后台获取操作期间可能不在内存中。创建一个单独的类或处理获取和存储数据的类,然后在您的 ViewControllers viewWillAppear 函数上加载最新的可用数据。

要测试后台获取操作,在 xcode 中,从菜单中选择“调试”,然后选择“模拟后台获取”。它将启动应用程序并调用 performFetchWithCompletionHandler 函数。

关于定期在后台快速运行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51131100/

相关文章:

swift - 无法将数据添加到 firebase

ios - swift : How to change language inside app?

swift - 在子类 SKSpriteNode 中创建 SKSpriteNode 是一个好习惯吗?

ios - 快速删除plist

ios - UINavigationBar.Appearance.BarTintColor 也影响我的标签栏背景颜色

ios - 如何获取ios 9中的数据模型?

ios - dyld:库未加载Xcode11

ios - 无法从 for 循环内返回值? swift

swift - 初始化计算变量

ios - 我在 pod install Kanna 时遇到错误