问题描述
我正在开发一个 iOS/Apple Watch 应用,其中包含一个计时器。设置计时器后,它会在计时器完成时设置本地警报以触发。当应用处于打开状态且处于前台时效果很好,但不会在锁定屏幕或切换应用时发出警报。
iOS 和 Watch 相同的行为
该应用程序正在请求 .alert
、.sound
和 .badge
权限,并且所有权限都被授予。
我试过在 x
秒内与在指定时间开火,行为相同
我看到有人说它需要运行超过 60 秒,这并没有改变结果。
相关代码:
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge]) { success,error in
if success {
print("Notification Permission Set")
} else if let error = error {
print(error.localizedDescription)
}
}
let content = UNMutableNotificationContent()
content.title = "LE Timer"
content.subtitle = "Timer Complete"
content.sound = UNNotificationSound.default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: runFor,repeats: false)
notificationId = UUID().uuidString
let request = UNNotificationRequest(identifier: notificationId,content: content,trigger: trigger)
UNUserNotificationCenter.current().add(request)
解决方法
发现问题:我有一个函数应该在计时器停止时删除通知,并且设置错误,因此它在计时器运行时删除了通知。我还最终设置了一个硬编码的通知 ID,该 ID 有效,因为不应该同时有 2 个警报。