[英]Swift 4 Repeating Local Notifications
我正在尝试发出一条将在每天的同一时间(7:00 AM)触发的通知。 如果我使用UNTimeIntervalNotificationTrigger
而不是UNCalendarNotificationTrigger
,那我就能得到要触发的通知,这正是我真正想要的。 这是我目前拥有的:
在AppDelegate.swift中,我有:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (didAllow, error) in
if error != nil {
print(error as Any)
}
}
return true
}
我记得也要导入UserNotifications
当用户按下ViewController.swift中的按钮时,将运行该命令:
let content = UNMutableNotificationContent()
content.title = "Do your daily review"
content.badge = 1
let triggerTime = DateComponents.init(hour: 7, minute: 0, second: 0)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerTime, repeats: true)
let request = UNNotificationRequest(identifier: "dailyNotification", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil
您能否向我解释一下这里出了什么问题,为什么UNTimeIntervalNotificationTrigger
可以工作,而UNCalendarNotificationTrigger
却不起作用?
我不确定它是否可以解决您的问题,但您是直接从init设置DateComponent。 我建议您通过初始化一个空的DateComponent并仅根据需要设置小时来做到这一点。
因此,您可以尝试执行以下操作:
let content = UNMutableNotificationContent()
content.title = "Do your daily review"
content.badge = 1
var triggerTime = DateComponents()
triggerTime.hour = 7
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerTime, repeats: true)
let request = UNNotificationRequest(identifier: "dailyNotification", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
我从自己的角度做到了,并且有效。
希望对您有所帮助。
我的原始代码运行良好,只需要以不同的方式进行测试即可。 出于某种原因,如果我将代码中的时间设置为7:00 AM,然后在Mac上模拟该时间,则该时间不起作用,但是如果我将其设置为实时时间+ 1分钟,并且我等待了一分钟,却没有改变计算机的时间,它可以正常工作。 也许Apple会在时间跳变后立即停止通知,以防止人们在更改时区时遇到通知问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.