Swift & FCM:从后台切换到前台时如何获取推送通知数据?



我正在Swift中配置推送通知。到目前为止,我有三个场景。

1 -应用程序在前台在前台,我认为我做的一切都是正确的,因为我确实收到了推送通知数据。

func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

print("userNotificationCenter willPresent")
let content = notification.request.content

UIApplication.shared.applicationIconBadgeNumber = 0
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()

completionHandler([.alert, .sound])

}

2 -用户点击推送通知横幅

func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
print("userNotificationCenter didReceive")
defer {
completionHandler()
}
guard response.actionIdentifier == UNNotificationDefaultActionIdentifier else {
return
}

let content = response.notification.request.content


UNUserNotificationCenter.current().removeAllDeliveredNotifications()
}

3 - App在后台,然后用户进入App在这种情况下,推送通知到达用户的手机。但是,它们不是点击推送通知本身,而是进入应用程序。我无法从推送通知

中获取任何信息。有没有人可以帮助如何配置第三个场景?谢谢你。

您需要考虑applicationState

UIApplication

。国家

//AppDelegate
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

switch UIApplication.shared.applicationState {
case .active:
print("Received push message from APNs on Foreground")
case .background:
print("Received push message from APNs on Background")
case .inactive:
print("Received push message from APNs back to Foreground")
}
}

当应用程序从后台到前台,UIApplication.Stateinactive

inactive is '应用程序正在前台运行,但没有接收事件。'

因此,我认为实现你想要的行为的最好方法是自己写。

例如,

//AppDelegate
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

switch UIApplication.shared.applicationState {
case .active:
print("Received push message from APNs on Foreground")
case .background:
print("Received push message from APNs on Background")
case .inactive:
print("Received push message from APNs back to Foreground")
guard let nav = window?.rootViewController as? UINavigationController,
let currentVC = nav.viewControllers.last else {return}
if currentVC is 'youWantViewController' { //if you want ViewController, use notification post
let name = Notification.Name(rawValue: K.Event.pushRequest)
NotificationCenter.default.post(name: name, object: nil)
} else { //move to you want ViewController
let vc = 'yourViewController'()
root.navigationController?.pushViewController(vc, animated: true)
}
}
completionHandler(.newData)
}

我希望这对你有帮助。