【Swift】Apple Watch(SwiftUI)とiPhone(Storyboard)の連携 備忘録

Qiitaで質問したもののChatGPTで解決したので記録しておきます。

https://qiita.com/3121041/questions/60c3b8eaf8a2a3bc2196

## ソースコード
```diff_swift:ViewController.swift
import UIKit
import WatchConnectivity

class ViewController: UIViewController, WCSessionDelegate {
    
    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: (any Error)?) {
    }
    
    func sessionDidBecomeInactive(_ session: WCSession) {
    }
    
    func sessionDidDeactivate(_ session: WCSession) {
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if WCSession.isSupported(){
            let session = WCSession.default
            session.delegate = self
            session.activate()
            // Do any additional setup after loading the view.
        }
    }


    @IBAction func a(_ sender: Any) {
+        if WCSession.default.isReachable{
            let aaa = "已"
            let message = ["send" :aaa.description]
            WCSession.default.sendMessage(message, replyHandler: {reply in print("reply")}, errorHandler: {error in print(error.localizedDescription)})
            print("pushed")
+           print("Message sent: \(message)")
+       }else{
+          print("Apple Watch is not reachable")
+       }
    
    }
    
    

}

class WatchConnector: NSObject, ObservableObject, WCSessionDelegate{
    
    override init() {
        super.init()
        if WCSession.isSupported() {
            WCSession.default.delegate = self
            WCSession.default.activate()
        }
    }
    
    func session(
        _ session: WCSession,
        activationDidCompleteWith activationState: WCSessionActivationState,
        error: Error?
    ) {
        print("activationDidCompleteWith state= \(activationState.rawValue)")
    }
    
    func sessionDidBecomeInactive(_ session: WCSession) {
        print("sessionDidBecomeInactive")
    }
    
    func sessionDidDeactivate(_ session: WCSession) {
        print("sessionDidDeactivate")
    }
    
    func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
        replyHandler(["send" : "OK"])
    }
    
}
```

```diff_swift:ContentView.swift
import SwiftUI
import WatchConnectivity

struct ContentView: View {
    
    @ObservedObject var connector = PhoneConnector()
    
    var body: some View {
        
            Text("\(self.connector.receivedMessage)")
        
    }
}

struct ContentView_Previews: PreviewProvider{
    static var previews: some View{
        ContentView()
    }
}

class PhoneConnector: NSObject, ObservableObject, WCSessionDelegate {
    @Published var receivedMessage = "未"
    
    override init() {
        super.init()
        if WCSession.isSupported() {
            let session = WCSession.default
            session.delegate = self
            session.activate()
        }
    }
    
    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: (any Error)?) {
        print("activationDidCompleteWith state= \(activationState.rawValue)")
    }

    
-   func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
+   func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void)  {
        print("didReceiveMessage: \(message)")
        
        DispatchQueue.main.async {
-           self.receivedMessage = message["send"] as! String
+           if let receivedText = message["send"] as? String {
+               self.receivedMessage = receivedText
+               print("Message updated to: \(receivedText)")
+           }
+           replyHandler(["status": "received"])
        }
    }
}

#Preview {
    ContentView()
}
```
## 結果

 <img src="https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/3898382/b350f1a2-ac2e-6d0f-8783-054065a1e053.gif" width=50%>


ボタンを押したらWatchのTextが"未"から"已"に変わりました。


## 参考サイト
https://tech-blog.cloud-config.jp/2022-04-07-apple-watch-app-method

https://devops-blog.virtualtech.jp/entry/20230105/1672886601

https://chatgpt.com/