如何让 iOS 应用程序在 Swift 中永远在后台运行? [英] How make iOS app running on background forever in Swift?

查看:229
本文介绍了如何让 iOS 应用程序在 Swift 中永远在后台运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个定期向网站发出 HTTP 请求的应用程序.该应用程序必须在后台运行,但可以唤醒或显示通知,具体取决于请求的响应.像WhatsApp的消息,但我没有网络服务器,只有设备检查http get请求的值.

I want to make an app that makes HTTP request to a website periodically. The app has to run in the background, but can wake up or show a notification, depending on a response of request. Like a message of WhatsApp, but I don't have a webserver, only the device check values of the http get request.

推荐答案

这可以通过 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.

这篇关于如何让 iOS 应用程序在 Swift 中永远在后台运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆