【发布时间】:2020-10-11 10:29:39
【问题描述】:
我正在尝试在我的应用中实现本地通知。这个想法是每天早上 9:00 向用户发送一个通知,其中包含不同的报价,但我遇到了一个错误,即始终显示通知的相同内容,即无休止地重复相同的报价。我该如何解决?这是我正在使用的代码,我尝试为每个发送的通知使用 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? -
我不是用它来重复通知吗?
-
如果您想发送不同的通知,请不要这样做。
-
我尝试将值从 true 更改为 false,但现在我收到一般通知时遇到问题
标签: ios swift notifications