ios - iOS 上的每日提醒

标签 ios swift notifications unusernotificationcenter

我使用以下代码来触发每日提醒:

let triggerDate = calendar.date(from: calendarComponents)
let triggerDaily = Calendar.current.dateComponents([.hour, .minute, .second], from: triggerDate!)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
let request = UNNotificationRequest(identifier: "daily-identifier", content: content, trigger: trigger)
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
//UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [identifier])
UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error) in
      if error != nil {
        debugPrint("center.add(request, withCompletionHandler: { (error)")
      } else {
        debugPrint("no error?! at request added place")
      }
    })

上面的代码允许我设置带有标识符daily-identifier的每日闹钟。由于我计划在代码中设置两个每日闹钟,因此我使用上面的代码并使用另一个标识符 second-daily-identifier 来触发另一个具有不同小时/分钟组合的闹钟。

我遇到的问题: 如果我使用代码

UNUserNotificationCenter.current().removeAllPendingNotificationRequests()

在添加请求之前,它将删除之前设置的警报(例如,如果我先添加“每日标识符”警报,那么当我添加“第二每日标识符”时将删除“每日标识符”警报.

如果我使用其他方法

UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [identifier])

专门删除我要设置的那个,然后效果很好。然而,我发现我再也无法阻止了。例如,如果我将标识符更改为“第三标识符”,那么已经设置的闹钟将永远在我的手机中。即使我删除了应用程序,我也无法删除它们。

我做错了什么?

最佳答案

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

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)
}

关于ios - iOS 上的每日提醒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45193111/

相关文章:

iOS 蓝牙 peripheralManagerDidUpdateState 从未调用过

iphone - Grand Central Dispatch - 加载时显示第一张图片?

swift - 应用程序 iCloud 文档目录在安装应用程序后无法加载文件

swift - 在 Swift 中更改定时器选择器函数中的 userInfo

iphone - 创建新版本应用程序时sqlite文件的更改

ios - 天真的 Git 设置,是否可以取消跟踪我的 .gitignore 中列出的文件?

ios - 如何将 UIPickerView Controller 中的图像或视频保存到文档目录?

Android通知小图标在通知抽屉中放大

iphone - 如何知道 iPhone 中的 MPMoviePlayerController 何时已暂停?

android - 如何在不显示通知的情况下更新未读计数