且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何让 iOS 应用程序在 Swift 中永远在后台运行?

更新时间:2023-01-05 13:07:14

这可以通过 iOS 后台执行指南.您需要在应用程序的功能中包含后台提取"选项,然后在应用程序委托中实现 application(_:performFetchWithCompletionHandler:) 方法.然后,当 iOS 认为是下载某些内容的好时机时,将调用此方法.您可以使用 URLSession 和相关方法下载您想要的任何内容,然后调用提供的完成处理程序,指示内容是否可用.

This can be done with the fetch capability mentioned in the iOS Background Execution guide. You need to include the 'Background fetch' option in your app's capabilities, and then implement the application(_:performFetchWithCompletionHandler:) method in your application delegate. Then, this method will be called when iOS think's it is a good time to download some content. You can use URLSession and the associated methods to download whatever you want, and then call the provided completion handler, indicating whether content was available.

请注意,这不允许您安排此类下载,或对它们何时(甚至是否)发生进行任何控制.操作系统只有在认为时机成熟时才会调用上述方法.Apple 的文档解释:

Note that this does not allow you to schedule such downloads, or have any control over when (or even if) they happen. The operating system will call the above method only when it decides that it is a good time. Apple's docs explain:

启用此模式并不能保证系统会随时为您的应用提供执行后台提取的时间.系统必须平衡您的应用程序获取内容的需求与其他应用程序和系统本身的需求.在评估该信息后,系统会在有良好机会时为应用提供时间.

Enabling this mode is not a guarantee that the system will give your app any time to perform background fetches. The system must balance your app’s need to fetch content with the needs of other apps and the system itself. After assessing that information, the system gives time to apps when there are good opportunities to do so.

举个例子,这里是一个基本的实现,它启动下载,然后如果我们得到一个好的响应,然后从现在开始安排一个本地通知十秒钟:

As an example, here is a basic implementation which initiates a download and then schedules a local notification for ten seconds from now if we get a good response:

func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    URLSession.shared.dataTask(with: URL(string: "http://example.com/backgroundfetch")!) { data, response, error in
        guard let data = data else {
            completionHandler(.noData)
            return
        }
        guard let info = String(data: data, encoding: .utf8) else {
            completionHandler(.failed)
            return
        }
        let content = UNMutableNotificationContent()
        content.title = "Update!"
        content.body = info

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)

        let request = UNNotificationRequest(identifier: "UpdateNotification", content: content, trigger: trigger)
        let center = UNUserNotificationCenter.current()
        center.add(request) { (error : Error?) in
            if let error = error {
                print(error.localizedDescription)
            }
        }
        completionHandler(.newData)
    }
}

本地和远程通知编程指南 应作为实现通知的参考.

The Local and Remote Notification Programming Guide should be used as the reference for implementing notifications.