我正在尝试使用按钮在Apple Watch模拟器上显示本地通知。这是代码:
@IBAction func buttonOne() {
print("button one pressed")
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "Notified!", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "This is a notification appearing!", arguments: nil)
// Deliver the notification in five seconds.
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5,
repeats: false)
// Schedule the notification.
let request = UNNotificationRequest(identifier: "Notify", content: content, trigger: trigger)
center.add(request) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
} else {
print("successful notification")
}
}
}
控制台已成功打印"成功通知,"但通知永远不会出现在手表模拟器上。我不知道为什么会这样
答案 0 :(得分:1)
1)在安排通知之前,请求权限。使用requestAuthorization
方法,例如:
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
// Enable or disable features based on authorization
}
2)如果应用程序在前台运行,通知将不会出现在监视面上。考虑到这一点,您可以使用 cmd + H 来隐藏应用。