2017-06-20 62 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]) } –