2017-06-20 67 views
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") 
     } 
    } 

} 

控制檯正在成功打印「成功通知」,但通知從不出現在手錶模擬器上。我不知道爲什麼這是

回答

0

1)在安排通知之前,請求權限。使用requestAuthorization方法,例如:如果應用程序在前臺運行

let center = UNUserNotificationCenter.current() 
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in 
    // Enable or disable features based on authorization 
} 

2)的通知不會對手錶表面出現。考慮到這一點,你可以使用cmd + H來隱藏應用程序。

+0

2)你也可以在前臺實現通知處理。您只需通過content.setValue(true,forKey:「shouldAlwaysAlertWhileAppIsForeground」)將此值添加到通知內容中,並且必須使您的類符合「UNUserNotificationCenterDelegate」並實現函數func userNotificationCenter(_ center:UNUserNotificationCenter, willPresent notification:UNNotification,withCompletionHandler completionHandler:@escaping(UNNotificationPresentationOptions) - > Void){完成處理程序([。alert,.badge]) } –