メインコンテンツにジャンプ

Watch __CAPGO_KEEP_0__ リポジトリ

GitHub

このガイドでは、Xcodeでプロジェクトを設定し、CapgoWatchSDKを統合し、SwiftUIで機能的なウォッチアプリを作成する方法について説明します。

前提条件

「前提条件」

開始する前に、以下を確認してください。

  • Xcode 15 またはそれ以降 (Mac App Storeからダウンロード)
  • macOS Sonoma またはそれ以降 (最新のwatchOS SDK)
  • 既存のCapacitor iOSプロジェクト (run npx cap add ios あなたがまだしていない場合)
  • Apple Developerアカウント (無料アカウントは開発用に機能します)

このガイドを完了した後、プロジェクトの構造は次のようになります

  • ディレクトリios/
    • ディレクトリApp/
      • ディレクトリApp/ iOSアプリ
      • App.xcodeproj
      • App.xcworkspace プロジェクトを開くにはこちらを使用してください
      • Podfile
    • ディレクトリMyWatch/ 新しいウォッチアプリ
      • ディレクトリMyWatch/ ウォッチアプリのソース
        • MyWatchApp.swift
        • ContentView.swift
        • ディレクトリAssets.xcassets/
      • MyWatch.xcodeproj

ステップ 1: iOS プロジェクトを開く

ステップ 1: iOS プロジェクトを開く
  1. あなたの Capacitor プロジェクトの ios/App フォルダ
  2. 開く App.xcworkspace (ダブルクリックで開くことができる .xcodeproj(ダブルクリックで開くことができる
  3. Xcode がプロジェクトをインデックス化するのを待つ
  1. ステップ 2: watchOSのターゲットを追加する ステップ 2: watchOSのターゲットを追加する

  2. Xcodeで

    • ファイル → 新規作成 → ターゲット… テンプレートの選択者に進むと、以下のようになります。 上部のタブ
    • 選択 アプリ
    • クリック 次へ
  3. 時計アプリの設定

    • 製品名: MyWatch (またはあなたの好きな名前)
    • チームApple Developerチームを選択してください
    • 組織識別子iOSアプリと一致するようにしてください(例えば、 app.capgo)
    • Bundle ID: 生成されます (例えば、 app.capgo.myapp.watchkitapp)
    • 言語:
    • Swiftユーザーインターフェイス
    • SwiftUIウォッチアプリの種類
    • : iOS用アプリ (既存のiOSアプリ用のアプリではない) 選択を外す 通知シーンを含める
    • (必要な場合は除く) 時計拡張機能を含める (必要な場合を除き)
  4. クリック 完了

  5. 「MyWatch」スキームを有効にするかどうか」という質問が出た場合、クリック 有効

ステップ 3: 時計アプリ設定の構成

「ステップ 3: 時計アプリ設定の構成」セクション
  1. プロジェクトナビゲーター(左側のサイドバー)で、プロジェクトを選択(上部の青いアイコン)

  2. ターゲットリストから「MyWatch」などの時計ターゲットを選択

  3. プロジェクトナビゲーター(左側のサイドバー)で、 一般 タブ:

    • 表示名: アプリアイコンの下に表示される名前 (例: "My App")
    • バンドル識別子: .watchkitapp
    • バージョン: iOS アプリのバージョンと一致する
    • ビルド:
  4. iOS アプリのビルド番号と一致する Go to 署名 & Capabilities

    • 有効化 自動署名管理
    • 選択する チーム
    • コンテキスト:Capgoのマーケティングサイト。ロール:短いUIラベルまたはナビゲーションアイテム。ページ/エリア:page sla.astro。メッセージキー`team_plan` (チームプラン)。
  5. Xcodeは自動的にプロビジョニングプロファイルを作成します 設定:

    • デプロイメント情報最小限のデプロイメント

セクションのタイトル「ステップ 4: CapgoWatchSDK を Swift Package Manager を使用して追加する」 WatchConnector 通信用クラス。

  1. Xcodeに移動し、 ファイル → パッケージ依存関係の追加…

  2. 検索フィールドに以下を入力します:

    https://github.com/Cap-go/capacitor-watch.git
  3. Enterを押して、Xcodeがパッケージを取得するのを待ちます。

  4. パッケージを設定:

    • 依存関係ルール: "メジャーバージョン以降のアップグレード" "8.0.0"
    • 追加 追加する製品を選択:
  5. 追加

    • 重要: 以下のものを選択してください CapgoWatchSDK
    • watchOSアプリ向けに特に設計されています。 watchOSアプリ向けに特に設計されています。 watchOSアプリ向けに特に設計されています。
    • watchOSアプリ向けに特に設計されています。 watchOSアプリ向けに特に設計されています。

Step 5: Watchアプリの実装

「Step 5: Watchアプリの実装」

さて、Watchアプリを作成しましょう 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()
}

Step 6: WatchConnectivity用のiOSアプリの設定

Section titled “Step 6: iOS WatchConnectivityの設定”

iOSアプリもWatchConnectivity機能が必要です。

  1. プロジェクトナビゲーターでプロジェクトを選択してください

  2. プロジェクト iOSアプリのターゲット ウォッチターゲットではありません

  3. Go to Signing & Capabilities タブ

  4. Click Capability

  5. Search for and add WatchConnectivity (利用可能であれば) または自動的に追加されるかもしれません

  6. CapgoプラグインのCapacitorはiOS側を自動的に処理しますが、Info.plistには次の内容を確認してください

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

ステップ 7: ビルドと実行

ステップ 7: ビルドと実行

シミュレータで実行

シミュレータで実行
  1. Xcodeウィンドウの上部のスキームセレクターから、ウォッチ用のスキームを選択してください

  2. ウォッチ用のシミュレータを選択してください

    • デバイスセレクターの右側のデバイスをクリックしてください
    • Apple Watchのシミュレータを選択してください (例: "Apple Watch Series 9 (45mm)")
  3. iPhoneとApple Watchの両方で動作するiOSシミュレータを起動するには、 実行 ボタン (▶️) をクリックするか、 Cmd + R

  4. iPhoneとApple Watchの両方で動作するiOSシミュレータが起動します。

  1. iPhoneをUSBで接続する

  2. iPhoneとApple Watchがペアになっていることを確認する

  3. ウォッチスキームを選択する

  4. 実機のApple Watchをデバイスリストから選択する

  5. 実行 実機で実行

  6. 初回:両方のデバイスでコンピュータを信頼する必要があるかもしれません

ステップ8:通信テスト

ステップ8:通信テスト

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()

トラブルシューティング

Section titled “Troubleshooting”
  1. バンドル ID が正しく関連付けられていることを確認してください (Watch アプリのバンドル ID は iOS アプリのバンドル ID +) .watchkitapp)
  2. 両方のアプリが同じチームで署名されていることを確認してください
  3. 物理デバイスで: iPhone の Watch アプリを開く → My Watch → アプリを探してスクロール → アプリを ON に切り替え
  1. 両方のアプリが WCSession を有効にしていることを確認してください
  2. 確認 isReachable メッセージを送信する前に
  3. 確実に配信されるようにするには transferUserInfo の代わりに sendMessage
  4. 他のデバイスがメッセージを送信する前にリスナが登録されていることを確認する

セッションが有効化されていない

セクション「セッションが有効化されていない」
  1. 呼び出し WatchConnector.shared.activate() コンテキスト: Appflowの比較/移行のマーケティングコピー (親キー `appflow_migration_step2`). ページ/エリア: ionic-appflow.astro. 役割: ウェブサイトのコピー文。
  2. アプリライフサイクル初期
  3. iOSではプラグインは自動的に有効になります - プラグインがインポートされていることを確認する

iOSのターゲットにWatchConnectivity機能が追加されていることを確認する

CapgoWatchSDKと関連するビルドエラー
  1. セクション「CapgoWatchSDKと関連するビルドエラー」 パッケージが追加されていることを確認する、iOSのターゲットではありません
  2. Clean build folder: Product → Clean Build Folder (Cmd + Shift + K)
  3. Reset package caches: File → Packages → Reset Package Caches

Simulator Issues

Simulatorの問題
  1. Reset the simulators: Device → Erase All Content and Settings
  2. iOSとwatchOSのシミュレータは互換性のあるペアであることを確認する
  3. 両方のシミュレータが実行されている必要があります。通信が機能するためには

Capgo Builder / native cloud build product page での場合 Creating a watchOS App ネイティブ プラグインの作業を計画するには、{0}に接続する必要があります。 Using @capgo/capacitor-watch for the native capability in Using @capgo/capacitor-watch, Capgo Plugin Directory for the product workflow in Capgo Plugin Directory, Capacitor Plugins by Capgo for the implementation detail in Capacitor Plugins by Capgo, プラグインの追加または更新の実装詳細のためにプラグインの追加または更新を使用する、 Ionic Enterprise プラグインの代替 Ionic Enterprise プラグインの代替の製品ワークフローのために Ionic Enterprise プラグインの代替を使用する ページを編集する