安装WatchKit Extension后UNTextInputNotificationAction无响应
问题
当应用安装WatchKit Extension后,Apple Watch端的UNTextInputNotificationAction运行异常:
- WatchKit Extension未在手表端显示安装时,UNTextInputNotificationAction可正常工作
- WatchKit Extension已在手表端安装显示后,点击UNTextInputNotificationAction按钮无任何响应
需要实现的效果:在WatchKit Extension已安装的场景下,点击按钮正常唤起标准UNTextInputNotificationAction输入交互。
现有通知注册代码:
public func registerForNotifications() { UNUserNotificationCenter.current().delegate = self let answerToChatAction = UNTextInputNotificationAction(identifier: "answerToChat", title: "Answer", options: [], textInputButtonTitle: "Send", textInputPlaceholder: "Type here…") let messageCategory = UNNotificationCategory(identifier: "ChatMessage", actions: [ answerToChatAction], intentIdentifiers: [], options: [.allowInCarPlay]) UNUserNotificationCenter.current().setNotificationCategories(Set([messageCategory])) let authOptions: UNAuthorizationOptions = [.alert, .sound, .badge] UNUserNotificationCenter.current().requestAuthorization( options: authOptions, completionHandler: { _, _ in }) DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } }
现有通知响应处理代码:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { switch response.actionIdentifier { case "answerToChat": answerOnPushInChat(response) default: print("Unknown action") } completionHandler() } fileprivate func answerOnPushInChat(_ response: UNNotificationResponse) { guard let userText = (response as? UNTextInputNotificationResponse)?.userText else { return } postMessage(message: userText).run() }
根本原因
WatchKit Extension安装到Apple Watch后,watchOS会默认将当前App的所有通知交互接管到Watch Extension侧处理,iOS端注册的通知Action、实现的通知代理不会在Watch端生效。当前代码仅在iOS端完成了通知配置,Watch Extension侧无对应注册和处理逻辑,因此点击Action按钮后系统找不到对应的处理逻辑,表现为无响应。
修复方案
按以下步骤配置即可恢复正常交互:
- 在Watch Extension侧同步注册相同的通知类别
在WatchKit Extension的启动入口(通常是ExtensionDelegate的applicationDidFinishLaunching方法)中,添加和iOS端identifier完全一致的UNTextInputNotificationAction、UNNotificationCategory配置,同时设置UNUserNotificationCenter.current().delegate为ExtensionDelegate/对应处理类。注意:Watch端不需要调用
UIApplication.shared.registerForRemoteNotifications,仅需完成类别注册即可。原有代码中给Category配置的.allowInCarPlay选项在Watch场景下无意义,建议移除,避免类别注册校验失败,无特殊需求options传空数组即可。 - 在Watch Extension侧实现通知响应代理方法
在Watch端的通知代理类中实现和iOS端逻辑一致的userNotificationCenter(_:didReceive:withCompletionHandler:)方法,识别answerToChat动作后获取UNTextInputNotificationResponse中的用户输入文本即可正常唤起输入交互。如果需要复用iOS端已有的消息发送逻辑,可以通过WatchConnectivity框架将Watch端收集到的用户输入文本回传给iOS端处理,不需要重复实现postMessage逻辑。 - (可选配置)如果需要Watch端在前台收到通知时也弹出系统通知横幅,额外实现
userNotificationCenter(_:willPresent:withCompletionHandler:)代理方法,回调时传入[.banner, .sound]展示选项即可。
内容的提问来源于stack exchange,提问作者AnHoncharenko
相关产品推荐
相关产品推荐

