应用程序终止时如何处理通知(iOS)

3
我正在开发一个应用程序,用于接收通知(使用苹果推送通知)。我将这些通知存储起来,并在一个控制器中显示为列表。据我所知,每当接收到通知时,都会调用didReceiveRemoteNotification方法。当应用程序处于前台或后台时,我可以从didReceiveRemoteNotification方法将通知存储在数据库中。但是当应用程序终止时,我该如何存储通知?
如果用户在应用程序终止时没有点击通知,则无法存储通知。如果用户在应用程序终止时点击通知,则可以通过使用启动选项存储通知。

@nyg 我的问题是关于在应用程序被终止时如何存储通知。链接是关于在后台状态而不是终止状态下处理通知的。 - Bharath Reddy
根据这个问题的答案https://dev59.com/kVsW5IYBdhLWcg3wXmS6,似乎没有存储通知的方法。但是在WhatsApp中可以正常工作。 - Bharath Reddy
1个回答

1

你尝试过使用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
    }
}

哦,我还没有尝试过这个。我会试一下并检查一下。谢谢你的回复。 - Bharath Reddy
@BharathReddy 很好!抱歉我之前将你的问题标记为重复,我没有完全理解你想要做什么... - nyg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接