如何触发WK通知
问题描述:
我需要编写哪些代码才能从手表应用程序本身触发手表套件通知?例如,如果我将手表故事板中的按钮作为动作连接到WatchInterfaceController,然后按下时它会在手表上触发通知。如何触发WK通知
答
为了测试手表通知,您必须先创建一个新的构建方案。
复制您的手表应用程序方案,并在“运行”部分选择您的自定义通知作为可执行文件。
现在您可以运行通知方案。
在项目中的扩展组内,在支持文件下是一个名为PushNotificationPayload.json的文件。
您可以编辑有效载荷文件以尝试不同的通知和类别。
答
触发一个通知,首先你需要权限:(在ExtensionDelegate声明通常)
func askPermission() {
UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .alert,.sound]) { (authBool, error) in
if authBool {
let okAction = UNNotificationAction(identifier: "ok", title: "Ok", options: [])
let category = UNNotificationCategory(identifier: "exampleCategoryIdentifier", actions: [okAction], intentIdentifiers: [], options: [])
UNUserNotificationCenter.current().setNotificationCategories([category])
UNUserNotificationCenter.current().delegate = self
}
}
}
对于有这方面的工作,你需要导入(在ExtensionDelegate)“UserNotifications”,并延长:
UNUserNotificationCenterDelegate
一旦你这样做,你可以调用askPermission哪里你想要,就像这样:
if let delegate = WKExtension.shared().delegate as? ExtensionDelegate {
delegate.askPermission()
}
现在你有(希望)的权限触发通知! 对于触发的通知,你可以使用这样的功能:
func notification() {
let content = UNMutableNotificationContent()
content.body = "Body Of The Notification"
content.categoryIdentifier = "exampleCategoryIdentifier" // Re-Use the same identifier of the previous category.
content.sound = UNNotificationSound.default() // This is optional
let request = UNNotificationRequest(identifier: NSUUID().uuidString,
content: content,
trigger: nil)
let center = UNUserNotificationCenter.current()
center.add(request) { (error) in
if error != nil {
print(error!)
} else {
print("notification: ok")
}
}
}
+0
谢谢!请考虑对我未解答的问题采取“一瞥”(笑)。 Incase你可以帮助我! –
谢谢您的回答,但呼吁在正常情况下的通知(一个真正的设备上没有在Xcode关联),我必须用什么代码的条款它被触发? –
这是不可能的。你应该使用像Pusher这样的远程通知提供者(这很容易实现)。所以当你进入他们的网络界面并发送推送通知时,它会出现在所有'订阅'的设备上。但是用按钮或类似的东西来触发它是不可能的。 –