【问题标题】:Xcode Apple Watch project, local notification not being presented?Xcode Apple Watch 项目,未显示本地通知?
【发布时间】:2017-06-20 19:19:01
【问题描述】:

我正在尝试在带有按钮的 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")
        }
    }

}

控制台正在成功打印“成功通知”,但该通知从未出现在手表模拟器上。我不知道为什么会这样

【问题讨论】:

    标签: xcode notifications watchkit


    【解决方案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 来隐藏应用程序。

    【讨论】:

    • 2) 您也可以在前台实现通知处理。您只需通过content.setValue(true, forKey: "shouldAlwaysAlertWhileAppIsForeground")将此值添加到您的通知内容中,并且必须使您的类符合UNUserNotificationCenterDelegate并实现函数func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.alert,.badge]) }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 2015-01-27
    相关资源
    最近更新 更多