2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめてのアドベントカレンダーAdvent Calendar 2024

Day 14

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

Posted at

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

ソースコード

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

結果

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

参考サイト

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?