You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断UNNotificationResponse来自Apple Watch扩展或iOS应用?

判断UNNotificationResponse的来源:Apple Watch vs iOS应用

嘿,这个问题问得很实用!我可以明确告诉你:完全可以在userNotificationCenter(_:didReceive:withCompletionHandler:)代理方法里判断用户是通过Apple Watch还是iOS设备与通知交互,具体方法如下:

核心判断逻辑

UNNotificationResponse自带了一个sourceIdentifier属性,Apple已经为我们定义好了对应的常量来区分来源:

  • 当用户在iOS主应用上处理通知时,sourceIdentifier的值为UNNotificationSourceIdentifier.default
  • 当用户在Apple Watch扩展上处理通知时,sourceIdentifier的值为UNNotificationSourceIdentifier.watchExtension

代码示例(Swift)

直接在代理方法里做判断即可:

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    // 根据来源区分处理逻辑
    switch response.sourceIdentifier {
    case UNNotificationSourceIdentifier.default:
        print("用户在iOS设备上与通知交互")
        // 这里写iOS端专属的处理代码,比如跳转对应页面、更新本地数据等
    case UNNotificationSourceIdentifier.watchExtension:
        print("用户在Apple Watch上与通知交互")
        // 这里写Watch端专属的处理代码,比如同步数据到Watch、触发本地提醒等
    default:
        print("未知的通知交互来源")
    }
    
    // 务必记得调用completionHandler,否则系统会认为你的处理未完成
    completionHandler()
}

注意事项

  • 这个API要求iOS 10+和watchOS 3+,如果你的项目最低适配版本覆盖这些系统,就可以放心使用
  • 即使你的Apple Watch应用是独立运行的(不依赖iOS主应用),这个判断逻辑依然有效,watchExtension标识符是专门针对Watch端通知交互的

内容的提问来源于stack exchange,提问作者Matthew Brown

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:12:49