如何让iOS应用程序永远在Swift上运行?

Aug*_*sto 4 notifications ios swift

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

Jum*_*hyn 7

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

请注意,这不允许您安排此类下载,也无法控制它们何时(或即使)发生.操作系统只有在确定是合适的时候才会调用上述方法.Apple的文档说明:

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

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

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

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