我正在尝试在我的应用程序中实现本地通知。 这个想法是每天上午9:00给用户发送一个通知,其中有一个不同的引用,但我遇到了一个bug,通知的相同内容总是显示,即同一个引用无休止地重复。 我该怎么修好呢? 这就是我正在使用的代码,并且我尝试为发送的每个通知使用UUID,但是它并没有带来改进。
let notificationCenter = UNUserNotificationCenter.current()
let options: UNAuthorizationOptions = [.alert, .sound]
notificationCenter.requestAuthorization(options: options) {
(didAllow, error) in
if !didAllow {
print("User has declined notifications")
}
}
notificationCenter.getNotificationSettings { (settings) in
if settings.authorizationStatus != .authorized {
print("Notifications not allowed")
}
}
let randomArrayNotificationQuote = Int(arc4random_uniform(UInt32(myQuotes.count)))
let randomArrayNotificationTitle = Int(arc4random_uniform(UInt32(myTitle.count)))
let content = UNMutableNotificationContent()
content.title = "\(myTitle[randomArrayNotificationTitle])"
content.body = "\(myQuotes[randomArrayNotificationQuote])"
content.sound = UNNotificationSound.default
content.categoryIdentifier = "com.giovannifilippini.philo"
// Deliver the notification
var dateComponents = DateComponents()
dateComponents.hour = 9
dateComponents.minute = 00
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let uuid = UUID().uuidString
let request = UNNotificationRequest.init(identifier: uuid, content: content, trigger: trigger)
notificationCenter.add(request) { (error) in
if error != nil {
print("add NotificationRequest succeeded!")
notificationCenter.removePendingNotificationRequests(withIdentifiers: [uuid])
}
}
这里的问题是触发器将repeats设置为true
让触发器=UNCalendarNotificationTrigger(DateMatching:dateComponents,Repeats:true)
您需要将其设置为false,并在每次希望安排不同的通知(不同的内容)时重新运行此方法