我正在尝试了解 iOS 在后台任务方面的实际可能性。 我有一个在后台运行并跟踪设备上位置变化的应用程序。
现在,是否可以向设备发送推送通知并让设备将当前位置发送到服务器而不需要用户打开应用程序以便它在前台运行?
最佳答案
我知道这个问题有点老了,但我正在为那些像我一样在问题被问到很久之后才来到这里的人回答。
Now, is it possible to send a push notification to the device and have the device send the current location to a server without needing the user to open the app so it runs in the foreground?
是的。你现在可以这样做了。我目前正在我的应用程序中做一些非常相似的事情。现在还有一些其他的 SO 问题可以正确地说明这一点。 This is one
基本上,您必须为远程通知
启用后台执行
。您可以通过转到应用程序的目标在 XCode 中执行此操作。打开 Capabilities
选项卡,启用 Background Modes
功能并选中 list 中的 Remote Notifications
项。 (我假设您已经启用了 Push Notifications
功能)。
有了这个,你用来在前台处理通知的代码也将在后台为你服务
application:didReceiveRemoteNotification:fetchCompletionHandler
方法将在您的应用程序处于后台时被调用。
这是 Swift 3.0 中的示例代码:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// Print full message.
print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
您可能想查看有关如何在后台处理网络请求的 SO 问题(和已接受的答案)。 Background request not execute Alamofire Swift
Check out the docs about Background Execution.特别是关于推送通知的部分
关于ios - 收到推送通知时在后台执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15288730/