0
我想用一個按鈕在Apple Watch模擬器上顯示本地通知。這是代碼:Xcode 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")
}
}
}
控制檯正在成功打印「成功通知」,但通知從不出現在手錶模擬器上。我不知道爲什麼這是
2)你也可以在前臺實現通知處理。您只需通過content.setValue(true,forKey:「shouldAlwaysAlertWhileAppIsForeground」)將此值添加到通知內容中,並且必須使您的類符合「UNUserNotificationCenterDelegate」並實現函數func userNotificationCenter(_ center:UNUserNotificationCenter, willPresent notification:UNNotification,withCompletionHandler completionHandler:@escaping(UNNotificationPresentationOptions) - > Void){完成處理程序([。alert,.badge]) } –