I would like to create an app that allows iOS and watchOS apps to exchange data in both directions, but I can't find instructions on how to do this anywhere. I would like to know how to do this in detail. import SwiftUI import WatchConnectivity
struct ContentView: View { @State private var receivedMessage: String = "No message received" @ObservedObject private var sessionDelegate = SessionDelegate()
var body: some View {
VStack {
Text(receivedMessage)
.padding()
Button("Receive from iPhone") {
sessionDelegate.sendMessageToiPhone()
}
}
.onAppear {
// WatchConnectivityセットアップ
sessionDelegate.setupWatchConnectivity()
}
}
}
struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
class SessionDelegate: NSObject, ObservableObject, WCSessionDelegate { @Published var receivedMessage: String = "No message received"
func setupWatchConnectivity() {
if WCSession.isSupported() {
let session = WCSession.default
if WCSession.isSupported() {
let session = WCSession.default
// デリゲートを設定
session.delegate = self
// セッションのアクティベーション状態を確認し、非アクティブな場合にアクティベートする
if session.activationState != .activated {
session.activate()
}
// セッションのその他の設
if WCSession.default.activationState == .activated {
// セッションがアクティブ
// ここでセッションがアクティブな場合の処理を実行
print("アクティブ")
} else {
// セッションがアクティブでない
// ここでセッションがアクティブでない場合の処理を実行
print("アクティブない")
}
}
session.delegate = self
if session.isReachable {
session.sendMessage(["messageKey": "Initial message"], replyHandler: nil, errorHandler: { error in
print("Error sending initial message to iPhone: \(error.localizedDescription)")
})
}
}
}
func sendMessageToiPhone() {
if WCSession.default.isReachable {
WCSession.default.sendMessage(["messageKey": "Request from Watch"], replyHandler: nil, errorHandler: { error in
print("Error sending request to iPhone: \(error.localizedDescription)")
})
}
}
// WCSessionDelegate メソッド
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
// セッションのアクティベーションが完了したときの処理
}
func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
if let receivedMessage = message["messageKey"] as? String {
DispatchQueue.main.async {
self.receivedMessage = receivedMessage
}
}
}
} I wrote the above code in contentView.swift in watchOS, but the session was not activated. I wonder if this is the cause.