应用程序终止时处理通知(iOS)
Handle Notifications when app is terminated(iOS)
我正在开发接收通知的应用程序(使用苹果推送通知)。我正在存储这些通知并在一个控制器中显示为列表。据我了解,无论何时收到通知,都会调用 didReceiveRemoteNotification。当应用程序处于前台和后台时,我可以通过 didReceiveRemoteNotification 方法将通知存储在 Db 中。但是当应用程序终止时,我该如何存储通知?
如果用户在应用程序终止时点击通知,我可以使用启动选项存储通知。但是,如果用户在应用程序终止时没有点击通知,我该如何存储通知?
您尝试过使用 getDeliveredNotifications(completionHandler:)
吗?您可以在例如调用以下代码您在其中显示收到的通知的控制器的 viewDidLoad 方法。
请注意,如果用户在通知中心清除收到的通知,这将不起作用。您必须按照您在评论中链接的问题的已接受答案中所述进行操作。
UNUserNotificationCenter.current().getDeliveredNotifications { notifications in
// notifications: An array of UNNotification objects representing the local
// and remote notifications of your app that have been delivered and are still
// visible in Notification Center. If none of your app’s notifications are
// visible in Notification Center, the array is empty.
// As said in the documentation, this closure may be executed in a background
// thread, so if you want to update your UI you'll need to do the following:
DispatchQueue.main.sync { /* or .async {} */
// update UI
}
}
我正在开发接收通知的应用程序(使用苹果推送通知)。我正在存储这些通知并在一个控制器中显示为列表。据我了解,无论何时收到通知,都会调用 didReceiveRemoteNotification。当应用程序处于前台和后台时,我可以通过 didReceiveRemoteNotification 方法将通知存储在 Db 中。但是当应用程序终止时,我该如何存储通知?
如果用户在应用程序终止时点击通知,我可以使用启动选项存储通知。但是,如果用户在应用程序终止时没有点击通知,我该如何存储通知?
您尝试过使用 getDeliveredNotifications(completionHandler:)
吗?您可以在例如调用以下代码您在其中显示收到的通知的控制器的 viewDidLoad 方法。
请注意,如果用户在通知中心清除收到的通知,这将不起作用。您必须按照您在评论中链接的问题的已接受答案中所述进行操作。
UNUserNotificationCenter.current().getDeliveredNotifications { notifications in
// notifications: An array of UNNotification objects representing the local
// and remote notifications of your app that have been delivered and are still
// visible in Notification Center. If none of your app’s notifications are
// visible in Notification Center, the array is empty.
// As said in the documentation, this closure may be executed in a background
// thread, so if you want to update your UI you'll need to do the following:
DispatchQueue.main.sync { /* or .async {} */
// update UI
}
}