ios - 收到推送通知时在后台执行代码

标签 ios geolocation push-notification apple-push-notifications

我正在尝试了解 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/

相关文章:

ios - 如何在特定位置的 uiimage View 上设置小图像?

iphone - 如何在 iphone 中创建警告框?

geolocation - GeoPositionAccuracy.High 有多高?

android - 当应用程序处于前台状态时,通知消息似乎为空

Android 推送通知消息格式

ios - 如何更改我的项目所在的 Xcode 工作区?

ios - 自定义 MKAnnotationView 可展开,无需标注

python - 用于在意大利 map 上呈现数据的 Bokeh

javascript - 使用 google api 进行反向查找来获取 iso 代码

ios - 消息发送成功但未出现在 ios 开发模式下的设备中