Skip to content

watchOSアプリの作成

GitHub

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

前提条件

前提条件

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

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

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

  • ディレクトリios/
    • ディレクトリApp/
      • ディレクトリ(あなたの主なiOSアプリ) App.xcodeproj
      • App.xcworkspace
      • __CAPGO_KEEP_0__ (このプロジェクトを開く)
      • Podfile
    • ディレクトリMyWatch/ (新しいウォッチアプリ)
      • ディレクトリMyWatch/ (ウォッチアプリのソース)
        • MyWatchApp.swift
        • ContentView.swift
        • ディレクトリAssets.xcassets/
      • MyWatch.xcodeproj
  1. iOSプロジェクトのCapacitorフォルダに移動してください ios/App フォルダ
  2. 開く App.xcworkspace (ファイル名を .xcodeproj)をダブルクリックして開く
  3. プロジェクトのインデックス作成を待つ
  1. Xcodeで、 ファイル → 新規 → ターゲット…

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

    • watchOS 上部のタブ watchOS
    • アプリ を選択
    • Click Next
  3. Configure your watch app:

    • Product Name: MyWatch (or your preferred name)
    • Team: Select your Apple Developer team
    • Organization Identifier: Should match your iOS app (e.g., app.capgo)
    • Bundle Identifier: Will be auto-generated (e.g., app.capgo.myapp.watchkitapp)
    • Language:Swift
    • ユーザー インターフェイス:SwiftUI
    • ウォッチ アプリのタイプ:アプリ(既存のiOSアプリ用のアプリではない)
    • チェックを外す 通知シーンを含める (必要な場合に限り)
    • チェックを外す 複合機能を含める (必要な場合に限り)
  4. クリック 完了

  5. 「MyWatch」スキームを有効にするかどうか”と尋ねられたらクリック 有効

  1. プロジェクトナビゲーター(左側のサイドバー)で、プロジェクト(上部の青いアイコン)を選択

  2. ターゲットリストから「MyWatch」という名前の時計ターゲットを選択

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

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

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

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

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

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

CapgoWatchSDKは通信用の WatchConnector classを提供します。

  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
    • 追加したことを確認してください watch target (e.g., “MyWatch”), not the iOS app
    • Click パッケージを追加

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

編集 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. Select your iOSアプリのターゲット (時計のターゲットではありません)

  3. Go to Signing & Capabilities タブ

  4. Click + Capability

  5. WatchConnectivityを検索して追加 (利用可能な場合) または自動的に追加されるかもしれません The __CAPGO_KEEP_0__ プラグインはiOS側を自動的に処理しますが、Info.plistには次の内容を確認してください:

  6. Capacitor

    <key>WKCompanionAppBundleIdentifier</key>
    <string>app.capgo.myapp.watchkitapp</string>
  1. Xcodeウィンドウの上部にあるスキームセレクターから、ウォッチスキームを選択してください。

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

    • デバイスセレクターの右側にあるスキームをクリックしてください
    • Apple Watchシミュレータを選択してください (例:「Apple Watch Series 9 (45mm)」)
  3. ▶️ボタンをクリックしてください 実行 実行ボタン (▶️) をクリックしてくださいまたは、Ctrl + R を押してください 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. Bundle IDが正しく関連付けられていることを確認する (watchアプリのBundle IDはiOSアプリのBundle ID + .watchkitapp)
  2. 両方のアプリが同じチームで署名されていることを確認する
  3. 物理デバイスで: iPhoneでWatchアプリを開く → My Watch → アプリを探してスクロール → アプリをONに切り替える

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

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

”Session Not Activated” Error

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

CapgoWatchSDKのビルドエラー

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

Capacitor を使用している場合 watchOS アプリの作成 ネイティブ プラグインの作業を計画するには、ネイティブ プラグインを接続する必要があります。 Using @capgo/capacitor-watch Using @capgo/capacitor-watch のネイティブ機能 Capgo プラグイン ディレクトリ Capgo プラグイン ディレクトリの製品ワークフローについて Capacitor Plugins by Capgo Capacitor プラグインの実装詳細については、Capgo プラグインの追加または更新 プラグインの追加または更新の実装詳細については、 Ionic Enterprise プラグインの代替 Ionic Enterprise プラグインの代替の製品ワークフローについて