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