0

我们有一个 iOS 应用程序,我们通过 FCM 向其发送通知。

理想情况下,我们希望能够让应用程序直接从通知中运行一些代码。

如果我们发送数据类型通知并且应用程序在前台,这似乎是可行的。

但是 - 如果 a) 应用程序在后台 b) 应用程序已终止,我们该怎么做。是否有某种方法可以自动运行应用程序,或者在应用程序终止时让应用程序自行备份。

谢谢

4

1 回答 1

1

应用程序在前台

在 AppDelegate 中实现didReceiveRemoteNotification委托方法来处理通知并在应用程序处于前台时运行您想要的代码。

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
    //write your code here when app is in foreground
}

应用程序在后台

当应用程序在后台并且用户收到推送通知时,如果用户点击通知,didReceiveRemoteNotification将被调用,但如果用户点击应用程序图标,则不会调用此方法,在这种情况下,您必须与您的服务器或您进行通信可以使用之前的值检查徽章编号(您可以将其存储在 NSUserDefaults 中)并运行您想要的代码。

应用程序已终止

当应用程序终止时,不会调用didReceiveRemoteNotification 方法,但是您可以在appdelegate 的didFinishWithLaunchOptions 方法中检查launchOptions了解应用程序是否已从通知启动,并相应地执行您的任务。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {

    if launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] != nil {
     // Do your task here
    }

}
于 2019-11-08T09:34:58.483 回答