Keril
Keril

Reputation: 39

The correct way to implement iOS - watchOS data sending

Problem is I don't know much about WatchConnectivity and it's implementation. Therefore, I can't understand why my provider class (WCSessionDelegate) with static property need to be initialized before its use on iOS and I think I'm doing something totally wrong. I'm using updateApplicationContext method to send selected data item on iOS app to watchOS app. I've read Apple docs about all other methods and I think this is the best option, because I need guaranteed data delivery, shortly. Now, I'm doing tests and to send data I need to click on Button() with send function 2+ times because on the first time of function call, I guess, iOS app doing init for WatchConnectivityProvider and session has no time to be initialized that fast. Here's the test example of my class:

class WatchConnectivityProvider: NSObject, WCSessionDelegate, ObservableObject {

    static let shared = WatchConnectivityProvider()

    private var session: WCSession?

    @Published var receivedMessage: String = ""
    private override init() {
        super.init()
        if WCSession.isSupported() {
            session = WCSession.default
            session?.delegate = self
            session?.activate()
        }
    }

    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
        //
    }

    #if os(iOS)
    func sessionDidBecomeInactive(_ session: WCSession) {
        print("Session Inactive")
        session.activate()
    }

    func sessionDidDeactivate(_ session: WCSession) {
        print("Session Deactivated")
        session.activate()
    }

    #endif

    func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
        DispatchQueue.main.async {
            if let text = applicationContext["message"] as? String {
                self.receivedMessage = text
            }
        }
    }

    public func updateApplicationContext(with context: [String: Any]) {
            do {
                try self.session?.updateApplicationContext(context)
            } catch {
                print("Updating of application context failed: \(error)")
            }
    }
}


So, to solve my problem I decided to use @StateObject in both of iOS and watchOS Views, like this:

@StateObject var connectivityProvider = WatchConnectivityProvider.shared

But is it a good solution?

Upvotes: 0

Views: 23

Answers (0)

Related Questions