Skip to content

Creating a watchOS App

GitHub

このプラグインの作成から始めて、Xcodeでプロジェクトを設定し、CapgoWatchSDKを統合し、SwiftUIで機能するウォッチアプリを作成するまでの手順を説明します。

前提条件

前提条件

始める前に、以下の条件を満たしてください。

  • Xcode 15 またはそれ以降 (Mac App Store からダウンロード)
  • macOS Sonoma またはそれ以降 (watchOS の最新版 SDK)
  • 既存の Capacitor iOS プロジェクト (実行する 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. Navigate to your Capacitor project’s ios/App フォルダ
  2. 開く App.xcworkspace (開かない .xcodeproj) をダブルクリックして開く
  3. Xcodeがプロジェクトをインデックス化するのを待つ

ステップ 2: watchOSのターゲットを追加する

ステップ 2: watchOSのターゲットを追加する
  1. Xcodeで、 ファイル → 新規作成 → ターゲット…

  2. テンプレートの選択者:

    • watchOS 上部のタブ watchOS
    • アプリ App
    • Click Next
  3. 時計アプリを設定する:

    • 製品名: MyWatch (または好みの名前)
    • チーム: Apple Developerチームを選択
    • 組織識別子: iOSアプリと一致するもの (例えば app.capgo)
    • バンドル識別子: 自動生成 (例えば app.capgo.myapp.watchkitapp)
    • 言語Swift
    • ユーザーインターフェイスSwiftUI
    • ウォッチアプリのタイプアプリ(既存のiOSアプリ用のアプリではない)
    • チェックを外す 通知シーンを含める (必要な場合は除く)
    • チェックを外す 複雑さを含める (必要な場合は除く)
  4. クリック 完了

  5. 「MyWatch」を有効化するように求められたら、 有効化

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

「ステップ 3: 時計アプリの設定」
  1. プロジェクトナビゲータ (左側のサイドバー) にて、プロジェクトを選択してください (上部の青いアイコン)

  2. ターゲットリストから、時計ターゲット (例: 「MyWatch」) を選択してください

  3. 「General」 「General」タブ: 表示名

    • : アプリアイコンの下に表示される名前 (例: 「My App」)__CAPGO_KEEP_0__
    • Bundle Identifier: __CAPGO_KEEP_0__に終わる .watchkitapp
    • Version: iOSアプリのバージョンと一致する
    • Build: iOSアプリのビルド番号と一致する
  4. Go to Signing & Capabilities tab:

    • Enable 自動的に署名を管理する
    • Select your チーム
    • Xcodeは自動的にプロビジョニングプロファイルを作成します
  5. 設定 デプロイメント情報:

    • 最小限のデプロイメント: watchOS 9.0 またはそれ以降

ステップ 4: CapgoWatchSDK を Swift Package Manager を使用して追加する

ステップ 4: CapgoWatchSDK を Swift Package Manager を使用して追加するというセクション

CapgoWatchSDKは、通信用の WatchConnector クラスを提供します。

  1. Xcodeで、 ファイル → パッケージ依存関係を追加…

  2. In the search field, enter: __CAPGO_KEEP_0__

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

  4. パッケージの設定:

    • 依存関係のルール: 「メジャーバージョン以降」に「8.0.0」
    • クリック パッケージを追加
  5. どの製品を追加するか選択:

    • 重要: 以下のものだけを選択 CapgoWatchSDK
    • 自分のプロジェクトに追加されていることを確認してください 目標プラットフォームを選択してください (例: “MyWatch”)、iOSアプリではなく
    • クリック パッケージ追加

Now let’s create the watch app code. Replace the auto-generated files with the following:

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

編集 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 に設定

セクション「ステップ 6: iOS アプリを WatchConnectivity に設定」

あなたの iOS アプリには WatchConnectivity 能力が必要です。

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

  2. を選択してください iOSアプリのターゲット (時計のターゲットではありません)

  3. に移動してください Signing & Capabilities タブ

  4. をクリックしてください Capability

  5. を検索して追加してください WatchConnectivity (利用可能な場合) または自動的に追加されるかもしれません

  6. The Capacitor plugin handles the iOS side automatically, but ensure your Info.plist has:

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

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

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

シミュレーターで実行

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

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

    • デバイスセレクターの右側のボタンをクリックしてください。
    • Apple Watchシミュレータを選択してください (例:「Apple Watch Series 9 (45mm)」)
  3. 実行ボタンをクリック (▶️) または Enter を押してください。 実行ボタン (▶️) をクリックしてください。 実行ボタン (▶️) をクリックしてください。 Cmd + R

  4. iOS シミュレータは、iPhone と Apple Watch の両方で起動します

  1. iPhoneをUSBで接続

  2. iPhoneとApple Watchがペアリングされていることを確認

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

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

  5. クリック 実行

  6. 初回:両方のデバイスでコンピューターを信頼する必要がある場合があります

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!' }
});
}

ウォッチアプリは 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でウォッチアプリを開き → マイウォッチ → アプリを探してスクロール → アプリをオンにします

メッセージが受信されていない

「メッセージが受信されていない」セクション
  1. 両方のアプリでWCSessionが有効になっていることを確認してください
  2. 確認 isReachable メッセージを送信する前に
  3. 確実に配信されるように transferUserInfo 代わりに sendMessage
  4. リスナが登録されていることを確認して、他のデバイスがメッセージを送信する前に

「セッションが有効になっていません」エラー

セッションが有効化されていません
  1. Call WatchConnector.shared.activate() アプリのライフサイクルが早くなる
  2. iOSではプラグインが自動的に有効化されます - プラグインがインポートされていることを確認してください
  3. iOSのターゲットにWatchConnectivity機能が追加されていることを確認してください

CapgoWatchSDKのビルドエラー

CapgoWatchSDKのビルドエラー
  1. パッケージがiOSターゲットではなく、watchターゲットに追加されていることを確認してください ビルドフォルダをクリーンするProduct → ビルドフォルダをクリーンする
  2. CapgoWatchSDKのビルドエラー パッケージがwatchターゲットに追加されていることを確認してください (Cmd + Shift + K)
  3. パッケージキャッシュをリセット: ファイル → パッケージ → パッケージキャッシュをリセット
  1. シミュレータをリセット: デバイス → 全てのコンテンツと設定を削除
  2. iOSとwatchOSのシミュレータが互換性のあるペアであることを確認する
  3. 両方のシミュレータが通信を実行するには実行中である必要がある

Capacitor を使用している場合 Creating a watchOS App Capacitor のネイティブプラグインの作業を計画する場合、Capacitor をネイティブキャパシティと接続します Using @capgo/capacitor-watch Capacitor のネイティブキャパシティのために Using @capgo/capacitor-watch Capgo プラグイン ディレクトリ Capgo プラグイン ディレクトリの製品ワークフローについて Capacitor プラグインは Capgo によって提供されます Capacitor プラグインの実装詳細については Capgo を参照してください プラグインの追加または更新 プラグインの追加または更新の実装詳細については、以下を参照してください Ionic Enterprise プラグインの代替 Ionic Enterprise プラグインの代替の製品ワークフローについて