跳过内容

创建 watchOS 应用

GitHub

本指南将指导您从零开始创建一个 watchOS 陪伴应用,包括在 Xcode 中设置项目、集成 CapgoWatchSDK 和使用 SwiftUI 构建一个功能性的手表应用。

在开始之前,请确保您有:

  • Xcode 15 或更高版本 (从 Mac App Store 下载)
  • macOS Sonoma 或更高版本 (用于最新的 watchOS SDK)
  • 一个现有的 Capacitor iOS 项目 (运行 npx cap add ios 如果你还没有)
  • 苹果开发者账户 (免费账户适用于开发)

项目结构概览

项目结构概览

完成本指南后,项目将具有以下结构:

  • 目录ios/
    • 目录App/
      • 目录App/ (您的主 iOS 应用)
      • App.xcodeproj
      • App.xcworkspace (用来打开项目的)
      • Podfile
    • 目录MyWatch/ (新手表应用)
      • 目录MyWatch/ (手表应用源码)
        • MyWatchApp.swift
        • ContentView.swift
        • 目录Assets.xcassets/
      • MyWatch.xcodeproj

步骤 1:在 Xcode 中打开您的 iOS 项目

标题:步骤 1:在 Xcode 中打开您的 iOS 项目
  1. Navigate to your Capacitor project’s ios/App 文件夹
  2. 打开 App.xcworkspace (不是 .xcodeproj)通过双击打开
  3. 等待 Xcode 索引项目

工作区包含了 CocoaPods 依赖项,这些依赖项是您的项目所需的。

步骤 2:添加 watchOS 目标
  1. 步骤 2:添加 watchOS 目标 在 Xcode 中,转到

  2. 文件 → 新建 → 目标…

    • 在模板选择器中: 选择 ‘watchOS’ 顶部标签
    • 选择 应用
    • 点击 下一步
  3. 配置您的手表应用:

    • 产品名称: MyWatch (或您的喜好名称)
    • 团队: 选择您的Apple Developer团队
    • 组织标识符: 应该与您的iOS应用匹配 app.capgo)
    • 应用程序标识符: 将自动生成(例如, app.capgo.myapp.watchkitapp)
    • 语言: 角色: UI 标签。位置: 组件文档/LanguageSelect.astro。消息键 `language_label` (语言标签)。
    • : Swift用户界面
    • : SwiftUIwatch 应用程序类型
    • : App (不是现有 iOS 应用程序) 取消 包含通知场景
    • (除非您需要它) 包含复杂度 (除非你需要)
  4. 点击 完成

  5. 当提示“激活 ‘MyWatch’ 方案?”时,点击 激活

步骤 3:配置手表应用设置

步骤 3:配置手表应用设置
  1. 在项目导航器(左侧侧边栏)中,选择您的项目(顶部蓝色图标)

  2. 从目标列表中选择您的手表目标(例如,“MyWatch”)

  3. 前往 通用 tab:

    • 显示名称显示名称:应用图标下方显示的名称(例如,“我的应用”)
    • 包标识符:应以 .watchkitapp
    • 版本:匹配iOS应用版本
    • 构建:匹配iOS应用构建号
  4. 前往 签名与功能 tab:

    • 启用 自动管理签名
    • 选择您的 团队
    • context: Capgo营销网站. 角色: 短 UI 标签或导航项. 见于: sla.astro 页面. 消息键 `team_plan` (团队计划).
  5. Xcode将自动创建配置文件 设置:

    • 部署信息最小部署

步骤 4: 通过 Swift Package Manager 添加 CapgoWatchSDK 的标题部分 WatchConnector 用于通信的类。

  1. 在 Xcode 中,前往 文件 → 添加包依赖项…

  2. 在搜索字段中输入:

    https://github.com/Cap-go/capacitor-watch.git
  3. 按 Enter 并等待 Xcode 获取包

  4. 配置包:

    • 依赖规则: “到下一个主要版本”与“8.0.0”
    • 点击 添加包
  5. 选择要添加的产品:

    • 重要提示: 仅选择 CapgoWatchSDK
    • 确保它已添加到您的 watch目标 (例如,“MyWatch”),而不是 iOS 应用
    • 点击 添加包

步骤 5:实现手表应用

步骤 5:实现手表应用

现在让我们创建手表应用 code. 将自动生成的文件替换为以下内容:

5.1 创建应用入口点

5.1 创建应用入口点

编辑 MyWatch/MyWatchApp.swift:

import SwiftUI
import CapgoWatchSDK
@main
struct MyWatchApp: App {
init() {
// Activate WatchConnectivity when app launches
WatchConnector.shared.activate()
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}

5.2 创建主视图

5.2 创建主视图

编辑 MyWatch/ContentView.swift:

import SwiftUI
import CapgoWatchSDK
struct ContentView: View {
// Observe the WatchConnector for automatic UI updates
@ObservedObject var connector = WatchConnector.shared
// Local state
@State private var messageText = ""
@State private var statusMessage = "Ready"
var body: some View {
ScrollView {
VStack(spacing: 16) {
// Connection Status
ConnectionStatusView(connector: connector)
Divider()
// Message Input
TextField("Message", text: $messageText)
.textFieldStyle(.roundedBorder)
// Send Buttons
HStack {
Button("Send") {
sendMessage()
}
.disabled(!connector.isReachable || messageText.isEmpty)
Button("Request") {
sendWithReply()
}
.disabled(!connector.isReachable || messageText.isEmpty)
}
Divider()
// Status
Text(statusMessage)
.font(.caption)
.foregroundColor(.secondary)
// Last Received Message
if !connector.lastMessage.isEmpty {
VStack(alignment: .leading) {
Text("Last Message:")
.font(.caption)
.foregroundColor(.secondary)
Text(formatMessage(connector.lastMessage))
.font(.caption2)
}
.frame(maxWidth: .infinity, alignment: .leading)
}
}
.padding()
}
}
private func sendMessage() {
connector.sendMessage(["text": messageText, "timestamp": Date().timeIntervalSince1970])
statusMessage = "Message sent"
messageText = ""
}
private func sendWithReply() {
connector.sendMessage(["text": messageText, "needsReply": true]) { reply in
DispatchQueue.main.async {
statusMessage = "Reply: \(formatMessage(reply))"
}
}
messageText = ""
}
private func formatMessage(_ message: [String: Any]) -> String {
message.map { "\($0.key): \($0.value)" }.joined(separator: ", ")
}
}
// Separate view for connection status
struct ConnectionStatusView: View {
@ObservedObject var connector: WatchConnector
var body: some View {
HStack {
Circle()
.fill(connector.isReachable ? Color.green : Color.red)
.frame(width: 12, height: 12)
Text(connector.isReachable ? "Connected" : "Disconnected")
.font(.headline)
Spacer()
if connector.isActivated {
Image(systemName: "checkmark.circle.fill")
.foregroundColor(.green)
}
}
}
}
#Preview {
ContentView()
}

步骤 6:配置 iOS 应用以支持 WatchConnectivity

Section titled “第 6 步:为 WatchConnectivity 配置 iOS 应用”

您的 iOS 应用还需要 WatchConnectivity 能力。

  1. 在 Project Navigator 中,选择您的项目

  2. 选择您的 iOS 应用目标 (不是 watch 目标)

  3. 转到 签名 & 能力 选项卡

  4. 点击 添加能力

  5. 搜索并添加 WatchConnectivity (如果可用) 或它可能会自动添加

  6. The Capacitor 插件会自动处理 iOS 端,但确保您的 Info.plist 文件包含:

    <key>WKCompanionAppBundleIdentifier</key>
    <string>app.capgo.myapp.watchkitapp</string>

第 7 步:构建和运行

标题:第 7 步:构建和运行

在模拟器上运行

标题:在模拟器上运行
  1. 从 Xcode 窗口顶部的方案选择器中选择您的 watch 方案

  2. 选择一个 Apple Watch 模拟器(例如,“Apple Watch Series 9 (45mm)”)

    • 点击设备选择器(位于方案选择器旁边)
    • 选择一个 Apple Watch 模拟器(例如,“Apple Watch Series 9 (45mm)”)
  3. 点击 运行 按钮 (▶️) 或按 Cmd + R

  4. iPhone 和 Apple Watch 将在 iOS 模拟器中启动

在真实设备上运行

标题:在真实设备上运行
  1. 连接您的 iPhone

  2. 确保您的 Apple Watch 与该 iPhonePair

  3. 选择您的 watch 方案

  4. 从设备列表中选择您的物理 Apple Watch

  5. 点击 运行

  6. 首次使用:您可能需要在两台设备上信任您的计算机

步骤 8:测试通信

步骤 8:测试通信

从 iPhone (Capacitor) 到 Watch

从 iPhone (Capacitor) 到 Watch

在您的 Capacitor 应用程序中:

import { CapgoWatch } from '@capgo/capacitor-watch';
// Check connection
const info = await CapgoWatch.getInfo();
console.log('Watch reachable:', info.isReachable);
// Send a message
if (info.isReachable) {
await CapgoWatch.sendMessage({
data: { action: 'update', value: 'Hello from iPhone!' }
});
}

从手表到iPhone

标题:从手表到iPhone

手表应用使用 WatchConnector:

// Send message (fire and forget)
WatchConnector.shared.sendMessage(["action": "buttonTapped"])
// Send message with reply
WatchConnector.shared.sendMessage(["request": "getData"]) { reply in
print("Got reply: \(reply)")
}

在iPhone上处理消息

标题:在iPhone上处理消息
// Listen for messages from watch
await CapgoWatch.addListener('messageReceived', (event) => {
console.log('Message from watch:', event.message);
// { action: 'buttonTapped' }
});
// Handle messages that need a reply
await CapgoWatch.addListener('messageReceivedWithReply', async (event) => {
console.log('Request from watch:', event.message);
// Send reply back
await CapgoWatch.replyToMessage({
callbackId: event.callbackId,
data: { status: 'success', items: ['item1', 'item2'] }
});
});

高级:自定义委托以获得更多控制

标题:高级:自定义委托以获得更多控制

如果您需要更多控制,请实现 WatchConnectorDelegate:

import SwiftUI
import CapgoWatchSDK
class WatchHandler: WatchConnectorDelegate {
func didReceiveMessage(_ message: [String: Any]) {
print("Received: \(message)")
// Handle incoming message
}
func didReceiveMessageWithReply(_ message: [String: Any],
replyHandler: @escaping ([String: Any]) -> Void) {
print("Received request: \(message)")
// Process and send reply
replyHandler(["status": "processed"])
}
func didReceiveApplicationContext(_ context: [String: Any]) {
print("Context updated: \(context)")
}
func didReceiveUserInfo(_ userInfo: [String: Any]) {
print("User info received: \(userInfo)")
}
func reachabilityDidChange(_ isReachable: Bool) {
print("Reachability changed: \(isReachable)")
}
func activationDidComplete(with state: WCSessionActivationState) {
print("Activation completed: \(state.rawValue)")
}
}
// In your app setup:
let handler = WatchHandler()
WatchConnector.shared.delegate = handler
WatchConnector.shared.activate()
  1. 确保包ID正确关联(手表应用包ID应为iOS应用包ID +” .watchkitapp)
  2. 检查两款应用都使用相同的团队签名
  3. 在物理设备上:在iPhone上打开手表应用 → 我的手表 → 滚动找到您的应用 → toggle ON
  1. 验证两款应用都激活了WCSession
  2. 检查 isReachable 在发送消息之前
  3. 为了保证消息的可靠传递,使用 transferUserInfo 取而代之 sendMessage
  4. 确保监听器在其他设备发送消息之前注册

会话未激活”错误

标题:”会话未激活”错误
  1. 调用 WatchConnector.shared.activate() 早期在应用生命周期
  2. 在 iOS 上,插件会自动激活 - 确保插件已导入
  3. 检查 iOS 目标中是否添加了 WatchConnectivity 能力

CapgoWatchSDK 构建错误

标题:CapgoWatchSDK 构建错误
  1. 确保包添加到 手表目标不支持iOS目标
  2. 清理构建文件夹: 产品 → 清理构建文件夹 (Cmd + Shift + K)
  3. 重置包缓存: 文件 → 包 → 重置包缓存

模拟器问题

模拟器问题
  1. 重置模拟器: 设备 → 擦除所有内容和设置
  2. 确保iOS和watchOS模拟器是兼容的对
  3. 两台模拟器都需要运行才能进行通信

下一步

下一步

继续创建 Apple Watch 应用

继续创建 Apple Watch 应用

如果您正在使用 创建 Apple Watch 应用 为native插件工作做好准备,连接它 使用@capgo/capacitor-watch 在使用@capgo/capacitor-watch时,native能力 Capgo插件目录 在Capgo插件目录中,Capgo插件 在Capacitor插件中,Capgo for the implementation detail in Capacitor Plugins by Capgo, 添加或更新插件的实现细节,并 Ionic企业插件替代方案 在Ionic企业插件替代方案中,产品流程 编辑页面