Monday, March 4, 2024
HomeiOS DevelopmentI need to ship messages from my iOS app and show them...

I need to ship messages from my iOS app and show them on Apple Watch


I need to ship messages from my iOS app and show them on Apple Watch, but it surely’s not working. Might you inform me what’s mistaken?

enter picture description right here

ViewController(iOS)

import UIKit
import WatchConnectivity

class ViewController: UIViewController, WCSessionDelegate {
    func sessionDidBecomeInactive(_ session: WCSession) {
        
    }
    
    func sessionDidDeactivate(_ session: WCSession) {
        
    }
    
    @IBOutlet weak var Text1: UITextField!
    @IBOutlet weak var Text2: UITextField!
    @IBOutlet weak var Text3: UITextField!
    @IBOutlet weak var SendButton: UIButton!
    
    var viewModel = MessageListViewModel()

    override func viewDidLoad() {
        tremendous.viewDidLoad()

        if WCSession.isSupported() {
            let session = WCSession.default
            session.delegate = self
            session.activate()
        }
    }

    // WCSessionDelegateのメソッド(必要に応じて実装)
    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
        // セッションのアクティベーションが完了したときの処理
    }

    @IBAction func sendButtonTapped(_ sender: UIButton) {
        sendTextsToWatch()
    }

    personal func sendTextsToWatch() {
        guard WCSession.default.isReachable else {
            // Apple Watchが到達不可能な場合の処理
            return
        }

        let texts = [
            "text1": Text1.text ?? "",
            "text2": Text2.text ?? "",
            "text3": Text3.text ?? ""
        ]

        WCSession.default.sendMessage(texts, replyHandler: nil) { error in
            print("Sending message failed: (error.localizedDescription)")
        }
    }
}

MessageListViewModel(iOS)

import Basis

import SwiftUI
import WatchConnectivity

ultimate class MessageListViewModel: NSObject, ObservableObject {
    // 配列に変化があれば変更を通知
    @Printed var messages: [String] = []

    var session: WCSession

    init(session: WCSession = .default) {
        self.session = session
        tremendous.init()
        self.session.delegate = self
        session.activate()
    }
}

extension MessageListViewModel: WCSessionDelegate {
    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
        if let error = error {
            print(error.localizedDescription)
        } else {
            print("The session has accomplished activation.")
        }
    }
    func sessionDidBecomeInactive(_ session: WCSession) {
    }
    func sessionDidDeactivate(_ session: WCSession) {
    }
    
}

ContentView(Apple Watch)

import SwiftUI
import WatchConnectivity
import Mix

// ContentViewの外にWCSessionWatchForReceivingクラスを移動
ultimate class WCSessionWatchForReceiving: NSObject, ObservableObject, WCSessionDelegate {
    @Printed var receivedText1 = "Ready for textual content 1..."
    @Printed var receivedText2 = "Ready for textual content 2..."
    @Printed var receivedText3 = "Ready for textual content 3..."

    override init() {
        tremendous.init()
        if WCSession.isSupported() {
            let session = WCSession.default
            session.delegate = self
            session.activate()
        }
    }

    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
        // セッションのアクティベーションが完了したときの処理
    }

    func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
        DispatchQueue.essential.async { [weak self] in
            self?.receivedText1 = message["text1"] as? String ?? "No textual content 1"
            self?.receivedText2 = message["text2"] as? String ?? "No textual content 2"
            self?.receivedText3 = message["text3"] as? String ?? "No textual content 3"
        }
    }
}

struct ContentView: View {
    @StateObject var viewModel = WCSessionWatchForReceiving()

    var physique: some View {
        VStack {
            Textual content(viewModel.receivedText1).padding()
            Textual content(viewModel.receivedText2).padding()
            Textual content(viewModel.receivedText3).padding()
        }
    }
}

WCSessionWatch(Apple Watch)

import WatchConnectivity

ultimate class WCSessionWatch: NSObject {

    var session: WCSession

    init(session: WCSession  = .default) {
        self.session = session
        tremendous.init()
        self.session.delegate = self
        session.activate()
    }
}

extension WCSessionWatch: WCSessionDelegate {
    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
        if let error = error {
            print(error.localizedDescription)
        } else {
            print("The session has accomplished activation.")
        }
    }
}

I added a watchOS App to an current iOS app, and I adopted the settings associated to it as described on this article.
(https://qiita.com/AS_atsushi/objects/77c2389a7f21f15c4865)



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments