咨询非独立Apple Watch App点击推送通知不打开App的可行方案
解决非独立Apple Watch App点击推送不打开App的问题
针对非独立Watch App(依赖iPhone App)的场景,要实现点击推送通知不打开Watch端App,可以通过以下两种可行方案:
方案1:利用Watch端UNUserNotificationCenterDelegate拦截通知点击
你之前用的handleAction()已被UserNotifications框架的代理方法替代,只需在Watch Extension的ExtensionDelegate中实现新逻辑,就能拦截点击动作且不唤起App:
- 让
ExtensionDelegate遵循UNUserNotificationCenterDelegate协议 - 在
applicationDidFinishLaunching()中设置通知中心的代理为自身 - 实现
userNotificationCenter(_:didReceive:withCompletionHandler:)方法,直接调用完成闭包,不执行任何打开App的操作
示例代码:
import WatchKit import UserNotifications class ExtensionDelegate: NSObject, WKExtensionDelegate, UNUserNotificationCenterDelegate { func applicationDidFinishLaunching() { // 设置通知中心代理 UNUserNotificationCenter.current().delegate = self } // 拦截通知点击动作 func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // 仅执行完成闭包,不做任何跳转或App唤起操作 completionHandler() } }
方案2:将通知交互路由到iPhone端处理
如果希望点击通知时唤起iPhone端App而非Watch端,可以通过配置通知类别与自定义动作实现:
在iPhone端注册通知类别:
在iPhone App的AppDelegate或SceneDelegate中,注册包含自定义动作的通知类别,设置动作唤起iPhone端App:import UserNotifications func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // 注册自定义通知动作 let openiPhoneAction = UNNotificationAction(identifier: "open_iPhone_app", title: "在iPhone查看", options: [.foreground]) let watchCategory = UNNotificationCategory(identifier: "watch_notification_category", actions: [openiPhoneAction], intentIdentifiers: [], options: []) UNUserNotificationCenter.current().setNotificationCategories([watchCategory]) return true }推送Payload指定类别:
推送的JSON payload中需指定category为上述注册的类别ID,示例:{ "aps": { "alert": { "title": "新通知", "body": "这是一条测试通知" }, "category": "watch_notification_category" } }此时Watch端收到通知后,会显示自定义的"在iPhone查看"按钮,点击后将唤起iPhone端App,而非Watch端App。若要隐藏默认的通知主体点击动作,可在注册类别时调整
options,或仅保留自定义动作。
注意:非独立Watch App的通知权限与配置由iPhone端主导,确保iPhone端已正确请求推送权限,且Watch端已开启通知接收。
内容的提问来源于stack exchange,提问作者Josh O'Connor
相关产品推荐
相关产品推荐

