시계 앱 만들기
설치 단계와 이 플러그인의 전체 마크다운 가이드를 포함한 설정 안내를 복사할 수 있습니다.
이 안내서에서는 Xcode에서 프로젝트를 설정하고 CapgoWatchSDK를 통합하여 스위프트 UI로 기능적인 watch 앱을 만드는 방법을 안내합니다.
필수 조건
필수 조건시작하기 전에 다음을 확인하세요.
- Xcode 15 이상 Mac App Store에서 다운로드
- macOS Sonoma 이상 최신 watchOS SDK를 위해
- 기존 Capacitor iOS 프로젝트 (run
npx cap add ios만약 아직도) - 애플 개발자 계정 (개발을 위해 무료 계정이 작동합니다)
프로젝트 구조 개요
제목이 "프로젝트 구조 개요"인 섹션이 가이드를 완료한 후 프로젝트는 이 구조를 가집니다:
디렉토리ios/
디렉토리App/
디렉토리App/ __CAPGO_KEEP_0__
- …
- __CAPGO_KEEP_1__
- __CAPGO_KEEP_2__ __CAPGO_KEEP_3__
- __CAPGO_KEEP_4__
__CAPGO_KEEP_5____CAPGO_KEEP_6__ __CAPGO_KEEP_7__
__CAPGO_KEEP_8__프로젝트 폴더 MyWatch/
- MyWatchApp.swift
- ContentView.swift
폴더Assets.xcassets/
- …
- MyWatch.xcodeproj
1단계: iOS 프로젝트를 Xcode에서 열기
1단계: iOS 프로젝트를 Xcode에서 열기- 당신의 Capacitor 프로젝트의
ios/App폴더 - 열기
App.xcworkspace(이것은.xcodeproj)을 열기 위해 두 번 클릭 - Xcode가 프로젝트를 인덱싱하는 것을 기다리세요
워크스페이스에는 CocoaPods 의존성이 포함되어 있습니다. 프로젝트가 필요로 하는 의존성을 포함하고 있습니다.
2단계: watchOS Target 추가-
2단계: watchOS Target 추가 Xcode에서
-
파일 → 새 항목 → Target…
- 템플릿 선택기에서: watchOS 선택 상단 탭
- 선택 앱
- 클릭 다음
-
시계 앱 설정:
- 제품 이름:
MyWatch(또는 선호하는 이름) - 팀: Apple 개발자 팀을 선택하세요
- 조직 식별자: iOS 앱과 일치해야 합니다 (예:
app.capgo) - Bundle Identifier: Will be auto-generated (e.g.,
app.capgo.myapp.watchkitapp) - 언어: Swift
- 사용자 인터페이스: SwiftUI
- Watch 앱 유형: 앱 (기존 iOS 앱이 아닌 앱)
- 해제 알림 장면 포함 (필요하지 않다면 해제)
- 해제 시계 확장 기능 활성화 (필요한 경우 제외)
- 제품 이름:
-
클릭 완료
-
‘MyWatch’ 시계 스키마 활성화提示를 받으면 클릭 활성화
3단계: 시계 앱 설정 구성
3단계: 시계 앱 설정 구성 섹션-
프로젝트 탐색기(왼쪽 사이드바)에서 프로젝트를 선택하세요(상단 blue 아이콘)
-
시계 대상(예: ‘MyWatch’)을 선택하세요
-
‘General’으로 이동 일반 탭:
- 표시 이름: 앱 아이콘 아래에 표시되는 이름 (예: "My App")
- Bundle 식별자: 끝에
.watchkitapp - 버전: iOS 앱 버전과 일치
- 빌드: iOS 앱 빌드 번호와 일치
-
바로가기 인증 및 기능 탭:
- 켜기 자동으로 서명 관리
- 선택하세요 팀
- 팀
-
Xcode는 자동으로 프로비저닝 프로파일을 생성합니다 설정:
- 배포 정보최소 배포
: watchOS 9.0 이상
4단계: Swift Package Manager를 통해 CapgoWatchSDK를 추가하세요Swift Package Manager를 통해 CapgoWatchSDK를 추가하세요 WatchConnector 통신을 위한 클래스.
-
In Xcode에서 다음으로 이동하세요. File → 패키지 종속성 추가…
-
검색 필드에 입력하세요:
https://github.com/Cap-go/capacitor-watch.git -
Enter를 누르고 Xcode가 패키지를 가져올 때까지 기다리세요.
-
패키지를 구성하세요:
- 의존성 규칙: "8.0.0
- Xcode에서 다음으로 이동하세요. File → 패키지 종속성 추가…
-
검색 필드에 입력하세요: Capgo CLI를 복사하고 붙여넣으세요. Enter를 누르고 Xcode가 패키지를 가져올 때까지 기다리세요. 패키지를 구성하세요: 의존성 규칙: "8.0.0" 다음으로 이동하세요: Add Package를 클릭하세요. Choose which products to add:
- 중요: 오직 선택
CapgoWatchSDK - watch target에 추가되어야 합니다. (예: "MyWatch"), iOS 앱이 아닌 클릭
- 패키지 추가 팁
- 중요: 오직 선택
5단계: 시계 앱 구현
5단계 시계 앱 구현 섹션시계 앱을 만들 차례입니다. code. 다음 파일을 자동 생성된 파일로 대체하세요.
5.1 앱 진입점 만들기
5.1 앱 진입점 만들기 섹션수정 MyWatch/MyWatchApp.swift:
import SwiftUIimport CapgoWatchSDK
@mainstruct 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 SwiftUIimport 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 statusstruct 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단계: WatchConnectivity를 위한 iOS 앱 구성
Step 6: WatchConnectivity를 위한 iOS 앱 구성iOS 앱도 WatchConnectivity 기능이 필요합니다.
-
프로젝트 탐색기에서 프로젝트를 선택하세요.
-
프로젝트 iOS 앱 목표 시계 목표가 아닌
-
목표를 선택하세요. 설정 탭
-
클릭 기능 추가
-
WatchConnectivity 기능 추가 WatchConnectivity (사용 가능 시) 또는 자동으로 추가될 수 있습니다.
-
Capacitor 플러그인은 iOS 측을 자동으로 처리하지만, Info.plist에 다음 항목이 포함되어야 합니다.
<key>WKCompanionAppBundleIdentifier</key><string>app.capgo.myapp.watchkitapp</string>
7단계: 빌드 및 실행
7단계: 빌드 및 실행심리모에 실행
심리모에 실행-
Xcode 창 상단의 스키마 선택기에서 시계 스키마를 선택하십시오.
-
시계 시뮬레이터를 선택하십시오:
- 장치 선택기 옆의 클릭하여 장치를 선택하십시오.
- Apple Watch 시뮬레이터를 선택하십시오 (예: "Apple Watch Series 9 (45mm)")
-
클릭 버튼 (▶️)을 클릭하거나 실행 버튼 (▶️)을 클릭하거나
Cmd + R -
iOS 시뮬레이터는 아이폰과 애플 워치가 모두 실행됩니다.
실제 기기에서 실행
제목이 "실제 기기에서 실행"인 섹션-
아이폰을 USB로 연결하세요.
-
아이폰과 연결된 애플 워치를 확인하세요.
-
워치 스키마를 선택하세요.
-
실제 기기에서 사용할 애플 워치를 장치 목록에서 선택하세요.
-
클릭 실행
-
처음 사용: 양쪽 기기에서 컴퓨터에 신뢰를 할당해야 할 수 있습니다
8단계: 통신 테스트
8단계: 통신 테스트iPhone (Capacitor)에서 시계로
iPhone (Capacitor)에서 시계로Capacitor 앱에서:
import { CapgoWatch } from '@capgo/capacitor-watch';
// Check connectionconst info = await CapgoWatch.getInfo();console.log('Watch reachable:', info.isReachable);
// Send a messageif (info.isReachable) { await CapgoWatch.sendMessage({ data: { action: 'update', value: 'Hello from iPhone!' } });}Watch에서 iPhone으로
Watch에서 iPhone으로Watch 앱은 WatchConnector:
// Send message (fire and forget)WatchConnector.shared.sendMessage(["action": "buttonTapped"])
// Send message with replyWatchConnector.shared.sendMessage(["request": "getData"]) { reply in print("Got reply: \(reply)")}iPhone에서 메시지 처리
iPhone에서 메시지 처리// Listen for messages from watchawait CapgoWatch.addListener('messageReceived', (event) => { console.log('Message from watch:', event.message); // { action: 'buttonTapped' }});
// Handle messages that need a replyawait 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'] } });});고급: 사용자 지정 위임자로 더 많은 제어
사용자 지정 위임자로 더 많은 제어더 많은 제어가 필요하다면 implement WatchConnectorDelegate:
import SwiftUIimport 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 = handlerWatchConnector.shared.activate()시계 앱이 시계에 나타나지 않는다
Section titled “시계 앱이 시계에 나타나지 않는다”- 시계 앱과 iOS 앱의 번들 ID가 올바르게 연결되어 있는지 확인하세요 (시계 앱의 번들 ID는 iOS 앱의 번들 ID +)
.watchkitapp) - 두 앱이 동일한 팀으로 서명되어 있는지 확인하세요
- 물리적 장치에서: iPhone에서 시계 앱을 열고 → My Watch → 앱을 찾으세요 → toggle ON
메시지가 수신되지 않는다
Section titled “메시지가 수신되지 않는다”- 두 앱이 WCSession이 활성화되어 있는지 확인하세요
- 확인하세요
isReachable메시지를 전송하기 전에 - 보장된 전달을 위해 사용하세요
transferUserInfo대신sendMessage - 다른 기기에서 메시지를 보내기 전에 리스너가 등록되어 있는지 확인하세요
세션 활성화되지 않았습니다
세션 활성화되지 않았습니다- Call
WatchConnector.shared.activate()애플리케이션 생명주기 초기에 - iOS에서 플러그인은 자동으로 활성화되기 때문에 플러그인을 임포트하세요
- iOS 대상에 WatchConnectivity 기능이 추가되어 있는지 확인하세요
CapgoWatchSDK와 관련된 빌드 에러
CapgoWatchSDK와 관련된 빌드 에러- 패키지가 추가되어 있는지 확인하세요 시계 대상에 패키지가 추가되어 있는지 확인하세요iOS가 아닌 대상
- 빌드 폴더를 깨끗하게하세요: Product → 빌드 폴더를 깨끗하게하세요 (Cmd + Shift + K)
- 패키지 캐시를 초기화하세요: File → Packages → 패키지 캐시 초기화
심화된 문제
Simulator Issues- 심뮬레이터를 초기화하세요: Device → 모든 콘텐츠와 설정을 초기화
- iOS와 watchOS 심뮬레이터가 호환되는 pair여야 합니다.
- 두 심뮬레이터 모두 동작해야 통신이 가능합니다.
다음 단계
다음 단계Creating a watchOS 앱에서 계속
Creating a watchOS 앱에서 계속만약에 Creating a watchOS 앱 native 플러그인 작업을 계획하려면, 그것을 연결하세요. Using @capgo/capacitor-watch native 기능을 사용하는 경우 Using @capgo/capacitor-watch Capgo 플러그인 디렉토리 제품 워크플로우를 사용하는 경우 Capgo 플러그인 디렉토리 Capacitor 플러그인들에 의해 Capgo implementation detail을 사용하는 경우 Capacitor 플러그인들에 의해 Capgo 플러그인을 추가하거나 업데이트 implementation detail을 사용하는 경우 플러그인을 추가하거나 업데이트, 그리고 Ionic Enterprise 플러그인 대체품 제품 워크플로우를 사용하는 경우 Ionic Enterprise 플러그인 대체품.