【问题标题】:How to cancel UserNotifications如何取消用户通知
【发布时间】:2017-03-26 13:34:19
【问题描述】:

如何禁用/取消已设置的通知?

这是我的日程安排功能。

func scheduleNotif(date: DateComponents, completion: @escaping (_ Success: Bool) -> ()) {

    let notif = UNMutableNotificationContent()

    notif.title = "Your quote for today is ready."
    notif.body = "Click here to open an app."

    let dateTrigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
    let request = UNNotificationRequest(identifier: "myNotif", content: notif, trigger: dateTrigger)

    UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in

        if error != nil {
            print(error)
            completion(false)
        } else {
            completion(true)
        }
    })
}

【问题讨论】:

    标签: ios swift xcode nsusernotification


    【解决方案1】:

    相同UNNotification 的识别方式基于创建UNNotificationRequest 时传递的identifier

    在你上面的例子中,

    let request = UNNotificationRequest(identifier: "myNotif", content: notif, trigger: dateTrigger)
    

    您实际上已将identifier 硬编码为"myNotif"。这样,每当您想删除已设置的通知时,您都可以这样做:

    UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: "myNotif")
    

    但是,请注意,当您对标识符进行硬编码时,每次将request 添加到UNUserNotificationCenter 时,通知实际上都会被替换。

    例如,如果您将 "myNotif" request 安排在 1 分钟后设置,但您调用另一个函数将 "myNotif" 安排在 1 小时后,它将被替换。因此,只有一小时后最新的"myNotif" 会在pendingNotificationRequest 中。

    【讨论】:

      【解决方案2】:

      要取消所有待处理的通知,您可以使用:

      UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
      

      对于取消特定通知,

      UNUserNotificationCenter.current().getPendingNotificationRequests { (notificationRequests) in
         var identifiers: [String] = []
         for notification:UNNotificationRequest in notificationRequests {
             if notification.identifier == "identifierCancel" {
                identifiers.append(notification.identifier)
             }
         }
         UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: identifiers)
      }
      

      【讨论】:

      • 在 AppDelegate 里面我们要调用这个函数的地方?,在 didReceiveRemoteNotificationapplication(received remoteMessage: MessagingRemoteMessage) 里面
      • 这是为了取消预定的本地通知。它可以从任何地方调用,因为UNUserNotificationCenter.current() 是一个单例对象
      【解决方案3】:

      here 所述,您可以使用以下代码取消所有通知:

      UIApplication.sharedApplication().cancelAllLocalNotifications()

      【讨论】:

        猜你喜欢
        • 2021-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多