Getting Started
复制一个包含安装步骤和本插件的完整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.
-
安装包
终端窗口 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);});
观察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)
标题:sendMessage(options: SendMessageOptions)向手表发送一个交互式消息。需要手表处于可接触状态。
参数:
data: Object - 将要发送到手表的数据
updateApplicationContext(options: UpdateContextOptions)
标题:updateApplicationContext(options: UpdateContextOptions)更新应用程序上下文。仅保留最新值。
参数:
context: Object - 需要同步的上下文数据
transferUserInfo(options: TransferUserInfoOptions)
Section titled “__CAPGO_KEEP_0__transferUserInfo(options: TransferUserInfoOptions)”确保用户信息可靠传递。
参数:
userInfo: Object - 需要传递的用户信息
replyToMessage(options: ReplyMessageOptions)
Section titled “__CAPGO_KEEP_0__replyToMessage(options: ReplyMessageOptions)”回复一个要求回复的消息。
参数:
callbackId: string - 消息接收回调 IDdata: Object - 回复数据
获取设备连接状态。
返回: WatchInfo object with:
isSupported: boolean - 是否 WatchConnectivity 可用isPaired: boolean - 是否配对手表isWatchAppInstalled: boolean - 是否安装手表应用isReachable: boolean - 是否手表可达成activationState: number - 会话状态 (0/1/2)
getPluginVersion()
Section titled “getPluginVersion()”获取本地插件版本。
Events
Section titled “Events”| Event | 描述 |
|---|---|
messageReceived | 来自手表的简单信息 |
messageReceivedWithReply | 来自手表的需要回复的信息(包含callbackId) |
applicationContextReceived | 来自手表的上下文更新 |
userInfoReceived | 来自手表的用户信息 |
reachabilityChanged | 手表连接状态改变 |
activationStateChanged | 会话激活状态改变 |
通信模式
关于通信模式的部分即时通讯(sendMessage)
需要手表可达- 适合交互式、时间敏感的通信
- 即时消息(sendMessage)
- 如果 watch 不可用,立即失败
应用上下文(updateApplicationContext)
应用上下文(updateApplicationContext)- 仅传递最新值,之前的值会被覆盖
- 最佳选择,用于同步当前应用状态
- 当 watch 可用时传递
用户信息传输(transferUserInfo)
用户信息传输(transferUserInfo)- 按顺序排队并传递
- 最佳选择,用于传递重要数据
- 即使 watch 暂时不可用,也能正常工作
平台说明
平台说明iOS
iOS- 需要 iOS 15.0 或更高版本
- 使用 WatchConnectivity 框架
- 在插件加载时会自动激活会话
- 支持在后台传递上下文和用户信息
Android
不支持(Apple Watch 只支持 iOS)- 所有方法都会以合适的错误拒绝
- 返回
getInfo()__CAPGO_KEEP_0__isSupported: false
Web
Web- 不支持
- 所有方法都以不可用错误拒绝
getInfo()返回isSupported: false
常见用例
常见用例- 数据同步:手机和手表数据保持同步
- :从手表控制手机功能:收到通知
- Notifications:
- : :
- : :
- : :
:
::
- :
- :
- 验证 WCSession 在两边都激活
未接收到的消息:
- 检查监听器在发送之前是否已注册
- 验证手表应用实现了 WCSessionDelegate
- 使用
transferUserInfo确保消息可靠送达
会话未激活:
- 确保在 Xcode 中添加了 WatchConnectivity 能力
- 检查手表应用是否有配对的 Bundle ID
- 验证两款应用都支持兼容的 OS 版本
继续从 Getting Started
继续从 Getting Started如果您正在使用 Getting Started 为原生插件工作而计划,连接它与 使用 @capgo/capacitor-watch 为原生能力在使用 @capgo/capacitor-watch 中 Capgo 原生插件目录 为产品工作流程在 Capgo 原生插件目录中 Capacitor 由 Capgo 提供的插件 为实现细节在 Capacitor 由 Capgo 提供的插件中 添加或更新插件 为实现细节在添加或更新插件中,和 Ionic Enterprise 原生插件替代方案 为 Ionic Enterprise Plugin Alternatives 产品工作流程.