【问题标题】:Is it possible to delete a notification seconds after sending it in Swift 5.4?是否可以在 Swift 5.4 中发送通知几秒钟后删除它?
【发布时间】:2021-08-13 13:56:18
【问题描述】:

我正在尝试编写一个函数,该函数发送包含私人用户数据的通知,可以使用以下代码在 5 秒后自动删除:

Button("Send Notification that self deletes after 5 seconds") {
                let content = UNMutableNotificationContent()
                content.title = "Notification Title"
                content.body = "Body"
                content.sound = UNNotificationSound.default
                
                let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
                
                let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
                
                UNUserNotificationCenter.current().add(request)
                
                DispatchQueue.main.asyncAfter(deadline: .now() + 10, execute: {
                    UNUserNotificationCenter.current().removeAllDeliveredNotifications()
                })

但是,通知仍然保留在通知中心和锁定屏幕上。我只能通过打开应用程序让UNUserNotificationCenter.current().removeAllDeliveredNotifications() 工作。我已经为这个答案搜索了几个小时的解决方案,但似乎找不到。非常感谢您的帮助。

【问题讨论】:

    标签: ios swift unusernotificationcenter


    【解决方案1】:

    您需要存储通知id

    let id = UUID().uuidString
    let request = UNNotificationRequest(identifier: id, content: content, trigger: trigger)
    

    然后您就可以使用removeDeliveredNotifications 删除它:

    UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [id])
    

    【讨论】:

    • 我试过了,还是不行。我不认为 id 是这里的问题。 removeDeliveredNotifications 仅在我再次启动应用程序时触发。
    • @cfyjdfk 是 removeDeliveredNotifications 当应用程序处于前台时调用的?
    • 我认为我无法对此进行测试,因为我只能在应用处于后台时接收来自应用的通知。一旦我收到通知并在前台运行应用程序,removeDeliveredNotifications 就会运行。
    • @cfyjdfk 如果您的应用程序在后台,您可以尝试使用后台作业来执行此操作。但是,如果您的应用程序很久以前被关闭或解雇,这将不起作用。唯一真正稳定的方法是使用服务器通知
    • 嗨,菲利普,很抱歉打扰您,但我不确定如何运行您提到的后台作业,即使在谷歌搜索之后也是如此,因为大多数解决方案都与 UIKit 相关。你能帮助我吗?提前致谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-13
    • 2016-01-13
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多