开始
复制一个包含安装步骤和此插件的完整 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 Implementation)
插件在加载时自动激活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);});
Watch App 实现
Watch 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)") }}sendMessage(options: SendMessageOptions)
名为“sendMessage(options: SendMessageOptions)”的部分向手表发送一个交互式消息。需要手表处于可达状态。
参数:
data: Object - 将要发送到手表的数据
updateApplicationContext(options: UpdateContextOptions)
名为“updateApplicationContext(options: UpdateContextOptions)”的部分更新应用程序上下文。仅保留最新值。
参数:
context: Object - 同步的上下文数据
transferUserInfo(options: TransferUserInfoOptions)
名为“transferUserInfo(options: TransferUserInfoOptions)”的部分为可靠传递排队用户信息
参数:
userInfo: Object - 将用户信息传递给
replyToMessage(options: ReplyMessageOptions)
标题:“回复消息(options:ReplyMessageOptions)”回复一个要求回复的消息。
参数:
callbackId: string - 从 messageReceivedWithReply 事件中获取的回调 IDdata: Object - 回复数据
getInfo()
标题:“获取信息()”获取手表连接状态。
返回值: WatchInfo 包含:
isSupported: boolean - 是否可用手表连接isPaired: boolean - 是否配对手表isWatchAppInstalled: boolean - 是否安装手表应用isReachable: boolean - 是否手表可达成activationState: number - 会话状态 (0/1/2)
getPluginVersion()
Section titled “getPluginVersion()”获取本地插件版本
Events
Section titled “Events”| Event | Description |
|---|---|
messageReceived | 手表发送简单消息 |
messageReceivedWithReply | 手表发送消息,期待回复(包含callbackId) |
applicationContextReceived | 上下文更新来自 watch |
userInfoReceived | 用户信息从 watch 转移 |
reachabilityChanged | 手表连接状态改变 |
activationStateChanged | 会话激活状态改变 |
通信模式
通信模式即时消息 (sendMessage)
标题:即时消息(sendMessage)- 需要手表可达成
- 适合交互式、时间敏感的通信
- 如果手表不可用,立即失败
应用上下文 (updateApplicationContext)
应用上下文(更新应用上下文)- 仅显示最新值 - 之前的值会被覆盖
- 最佳选择,用于同步当前应用状态
- 当手表可用时会被发送
用户信息传输(传输用户信息)transferUserInfo)
排队并按顺序发送- 最佳选择,用于传输必须被发送的重要数据
- 即使手表暂时不可用,也能正常工作
- 平台说明
Section titled “User Info Transfer (transferUserInfo)”
iOS- 需要 iOS 15.0 或更高版本
- 使用 WatchConnectivity 框架
- 会话在插件加载时自动激活
- 支持后台传递上下文和用户信息
Android
标题:Android- 不受支持(Apple Watch 只支持 iOS)
- 所有方法都会以合适的错误拒绝
getInfo()返回isSupported: false
Web
标题:Web- 不支持
- 所有方法都会以不可用错误拒绝
getInfo()返回isSupported: false
常见用例
标题为“常见用例”- 数据同步: 保持手表和手机数据同步
- 远程控制: 从手表控制手机功能
- 通知: 向手表发送自定义通知
- 健康数据: 分享健康和健身指标
- Media Control: 从手表控制音乐播放
- 智能家居: 从手腕控制设备
故障排除
- : 页面标题
- 手表不可达:
- 确保手表在蓝牙范围内
检查两款应用程序是否正在运行中
- 检查监听器是否已注册之前发送
- 验证 Watch 应用程序实现了 WCSessionDelegate
- 使用
transferUserInfo确保交付
会话未激活:
- 确保在 Xcode 中添加 WatchConnectivity 能力
- 检查 Watch 应用程序是否具有伴侣包 ID
- 验证两款应用程序都支持兼容的操作系统版本
继续从 Getting Started
标题为“继续从 Getting Started”如果您正在使用 Getting Started 为native插件工作做出计划,连接它 使用@capgo/capacitor-watch 在使用@capgo/capacitor-watch中 Capgo插件目录 在Capgo插件目录中 Capacitor由Capgo提供的插件 在Capacitor由Capgo提供的插件中 添加或更新插件 在添加或更新插件中 Ionic企业插件替代品 在Ionic企业插件替代品中