开始入门
复制一个包含安装步骤和本插件完整 Markdown 指南的配置提示。
Set up this Capacitor plugin in the project.
Use the package manager already used by the project.
Install these package(s): `@capgo/capacitor-watch`
Run the required Capacitor sync/update step after installation.
Read this markdown guide for the full setup steps: https://raw.githubusercontent.com/Cap-go/website/refs/heads/main/apps/docs/src/content/docs/docs/plugins/watch/getting-started.mdx
Use that guide for platform-specific steps, native file edits, permissions, config changes, imports, and usage setup.
If that guide references other docs pages, read them too.
安装
标题为“安装”您可以使用我们的 AI 助手设置来安装插件。将 Capgo 技能添加到您的 AI 工具中,使用以下命令:
npx skills add https://github.com/Cap-go/capgo-skills --skill capacitor-plugins然后使用以下提示:
Use the `capacitor-plugins` skill from `Cap-go/capgo-skills` to install the `@capgo/capacitor-watch` plugin in my project.如果您更喜欢手动设置,请运行以下命令并按照以下平台特定的说明进行安装:
-
安装包
终端窗口 bun add @capgo/capacitor-watch -
同步本地项目
终端窗口 bunx cap sync -
配置插件
基本使用示例:
import { CapgoWatch } from '@capgo/capacitor-watch';// Check watch connectivity statusconst info = await CapgoWatch.getInfo();console.log('Watch paired:', info.isPaired);console.log('Watch reachable:', info.isReachable);// Listen for messages from watchawait CapgoWatch.addListener('messageReceived', (event) => {console.log('Message from watch:', event.message);});向 Watch 发送消息:
// Check if watch is reachable firstconst info = await CapgoWatch.getInfo();if (info.isReachable) {await CapgoWatch.sendMessage({data: { action: 'refresh', timestamp: Date.now() }});}必备 iOS 设置:
- 在 Xcode 中为您的 iOS 应用程序添加 WatchConnectivity 能力
- 在 Xcode 项目中创建一个 watchOS 应用程序目标
- 在您的 watchOS 应用程序中实现 WatchConnectivity (参见下面的 Watch App 实现)
插件在加载时自动激活 WCSession。
Apple Watch 只在 iOS 上支持。 在 Android 上,所有方法都会以“Apple Watch 只在 iOS 上支持”错误拒绝。
getInfo()方法返回isSupported: false. -
处理需要回复的消息
// Listen for messages that need a responseawait CapgoWatch.addListener('messageReceivedWithReply', async (event) => {console.log('Request from watch:', event.message);// Process the requestconst result = await processWatchRequest(event.message);// Send reply back to watchawait CapgoWatch.replyToMessage({callbackId: event.callbackId,data: { result }});}); -
同步应用程序状态
// Update application context (latest value only)await CapgoWatch.updateApplicationContext({context: {theme: 'dark',userId: '123',lastSync: Date.now()}});// Listen for context updates from watchawait CapgoWatch.addListener('applicationContextReceived', (event) => {console.log('Context from watch:', event.context);}); -
可靠地传输用户信息
// Queue data for reliable delivery (even when watch is offline)await CapgoWatch.transferUserInfo({userInfo: {recordId: '456',action: 'created',data: { name: 'Item 1' }}});// Listen for user info transfersawait CapgoWatch.addListener('userInfoReceived', (event) => {console.log('User info from watch:', event.userInfo);}); -
监控网络连接
// Track reachability changesawait CapgoWatch.addListener('reachabilityChanged', (event) => {console.log('Watch reachable:', event.isReachable);if (event.isReachable) {// Watch is now available for interactive messaging}});// Track session activation stateawait CapgoWatch.addListener('activationStateChanged', (event) => {// 0 = notActivated, 1 = inactive, 2 = activatedconsole.log('Session state:', event.state);});
观察App实现
观察App实现您的watchOS应用程序需要实现WatchConnectivity。以下是SwiftUI示例:
import SwiftUIimport WatchConnectivity
@mainstruct MyWatchApp: App { init() { WatchViewModel.shared.activate() }
var body: some Scene { WindowGroup { ContentView() } }}
class WatchViewModel: NSObject, ObservableObject, WCSessionDelegate { static let shared = WatchViewModel()
@Published var lastMessage: [String: Any] = [:]
func activate() { guard WCSession.isSupported() else { return } WCSession.default.delegate = self WCSession.default.activate() }
// Send message to iPhone func sendToPhone(_ data: [String: Any]) { guard WCSession.default.isReachable else { print("iPhone not reachable") return } WCSession.default.sendMessage(data, replyHandler: nil) }
// Send message with reply func sendToPhoneWithReply(_ data: [String: Any], completion: @escaping ([String: Any]) -> Void) { guard WCSession.default.isReachable else { return } WCSession.default.sendMessage(data, replyHandler: completion) }
// Receive message from iPhone func session(_ session: WCSession, didReceiveMessage message: [String: Any]) { DispatchQueue.main.async { self.lastMessage = message } }
// Receive application context func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String: Any]) { DispatchQueue.main.async { self.lastMessage = applicationContext } }
// Required delegate methods func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { print("Watch session activated: \(activationState.rawValue)") }}API参考
API参考方法
方法sendMessage(options: SendMessageOptions)
Section titled “sendMessage(options: SendMessageOptions)”向手表发送交互式消息。需要手表保持可达。
参数:
data: Object - 需要发送到手表的数据
updateApplicationContext(options: UpdateContextOptions)
Section titled “updateApplicationContext(options: UpdateContextOptions)”更新应用程序上下文。仅保留最新值。
参数:
context: Object - 需要同步的上下文数据
transferUserInfo(options: TransferUserInfoOptions)
Section titled “transferUserInfo(options: TransferUserInfoOptions)”排队用户信息以确保可靠的传递。
参数:
userInfo: Object - 需要传输的用户信息
replyToMessage(options: ReplyMessageOptions)
Section titled “回复消息(options: 回复消息选项)”回复一个要求回复的消息。
参数:
callbackId: string - 从 messageReceivedWithReply 事件中获取的回调 IDdata: Object - 回复数据
getInfo()
Section titled “getInfo()”获取手表连接状态。
返回: WatchInfo 对象中包含:
isSupported: boolean - 是否可用isPaired: boolean - 是否配对isWatchAppInstalled: boolean - 是否安装手表应用isReachable: boolean - 是否 watch 可达activationState: number - 会话状态 (0/1/2)
getPluginVersion()
getPluginVersion()获取本地插件版本。
事件
事件| 事件描述 | 来自手表的简单消息 |
|---|---|
messageReceived | 来自手表的消息(包含回调 ID) |
messageReceivedWithReply | 来自手表的上下文更新 |
applicationContextReceived | 来自手表的用户信息传输 |
userInfoReceived | __CAPGO_KEEP_0__ |
reachabilityChanged | 连接状态改变 |
activationStateChanged | 会话激活状态改变 |
通信模式
通信模式即时消息(sendMessage)
即时消息(sendMessage)- 需要手表可达成
- 适合交互式、实时通信
- 立即失败,如果手表不可用
应用上下文(updateApplicationContext)
应用上下文(updateApplicationContext)- 仅最新值 - 之前值将被覆盖
- 最适合同步当前应用状态
- 当手表可用时发送
用户信息传输(transferUserInfo)
用户信息传输(transferUserInfo)- 按顺序排队并发送
- 最适合必须传递的重要数据
- 即使手表暂时不可用也能工作
平台说明
平台说明iOS
iOS- 需要 iOS 15.0 或更高版本
- 使用 WatchConnectivity 框架
- 会话在插件加载时自动激活
- 支持在后台传递上下文和用户信息
Android
Android 部分- 不支持(Apple Watch 只支持 iOS)
- 所有方法都以合适的错误拒绝
getInfo()返回isSupported: false
Web
Web 部分- 不支持
- 所有方法都以不可用错误拒绝
getInfo()returnsisSupported: false
常见用例
常见用例- 数据同步:手机和手表数据保持同步
- :从手表控制手机功能:向手表发送自定义通知
- :共享健康和健身指标:控制媒体播放
- Media Control控制媒体
- Media Control: 从手表控制音乐播放
- 智能家居: 从手腕控制设备
故障排除
故障排除手表不可达:
- 确保手表在蓝牙范围内
- 检查两款应用程序是否正在运行
- 在两边都激活WCSession
未接收到的消息:
- 检查监听器在发送之前是否已注册
- 在手表应用程序中实现WCSessionDelegate
- 使用
transferUserInfo确保送达
会话未激活:
- 确保在 Xcode 中添加 WatchConnectivity 能力
- 检查手表应用是否具有伴侣包 ID
- 验证两款应用都支持兼容的操作系统版本
继续从 Getting Started
继续从 Getting Started如果您正在使用 Getting Started 来规划原生插件工作,连接它与 使用 @capgo/capacitor-watch 为使用 @capgo/capacitor-watch 的本地能力 Capgo 插件目录 为 Capgo 插件目录中的产品流程 Capacitor 由 Capgo 提供的插件 为 Capacitor 由 Capgo 提供的插件中的实现细节 添加或更新插件 为添加或更新插件中的实现细节 Ionic 企业插件替代方案 为 Ionic 企业插件替代方案中的产品流程