如何解决UNCalendarNotificationTrigger 不适用于本地通知
尽管在这段代码上花费了数天时间,但我仍然无法让它按应有的方式触发。已经在线查看了许多最近的教程,我的代码与它们都匹配,但在构建到模拟器或设备时仍然无法正常运行。我想要的只是在每天的特定时间触发本地通知(显示的代码在上午 10:12 尝试)。部署目标是 iOS 14.3,我使用的是最新的 swift 5。 无奈之下,我什至尝试使用时间间隔 UNTimeIntervalNotificaitonTrigger 方法来创建到第二天的时间跨度,但这在设备和模拟器上的测试非常零星(有时在秒或分钟)但是,我希望它在每天的特定时间启动。
我没有在 appDelegate 或 sceneDelegate 中编写任何代码,因为我遵循的教程根本没有。所有这些代码都是我希望从中授权通知的 ViewController 的 viewDidLoad(如果有区别,这不是初始视图控制器)。求救!
//STEP 1 - Ask user for permission to notify
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.badge,.sound]) { success,error in
if success {
// TO REMOVE NOTIFICAITONS: UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
print("All set with User Authorisation!")
} else if let error = error {
print("Oh No,Authorisation did not work: ",error.localizedDescription)
}
}
//STEP 2 - Create Notification Content
let content = UNMutableNotificationContent()
content.title = "Daily Notification TITLE"
content.subtitle = "Hey - this is your daily notification SUBTITLE"
content.body = "This is the BODY of your daily notification"
content.sound = UNNotificationSound.default
//STEP 3 - Set up the Trigger by time each day
var triggerTime = DateComponents()
triggerTime.hour = 10
triggerTime.minute = 12
let myNotificationTrigger = UNCalendarNotificationTrigger(dateMatching: triggerTime,repeats: true)
// STEP 4 - Creating the Request
let request = UNNotificationRequest(identifier: UUID().uuidString,content: content,trigger: myNotificationTrigger)
// Step 5 - Register the Request
UNUserNotificationCenter.current().add(request) { (error) in
if let error = error{
print("Error has occured: \(error.localizedDescription)")
} else {
print("Added Notification: \(UUID().uuidString)")
}
}
} // END OF THE viewDidLoad bracket
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。