Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

swift - Why can my Apple Watch OS app receive message from my iOS app only when it is active?

I am trying to build a jogging app that communicates with the Apple Watch app. When I press the "Start" button, the iOS app should signal my Watch app to start keeping track of my workout. (e.g. Showing time elapsed, measure heart rate, and etc) To make that possible, the iOS and WatchOS app should communicate. The problem with my app is that my WatchOS app can only receive a signal from my iOS app when it is on. (e.g. Watch screen is on)

This is a code from my iOS app:

@objc func startAction() {
                 
    if WCSession.isSupported() {
        print("WC session is supported...")
        let session = WCSession.default
        session.delegate = self
        session.activate()

        session.sendMessage(["testWorkout":true], replyHandler: nil) { error in
            print("ERROR: (error.localizedDescription)")
        }
    }    
}

And this is code from the other end (From the watch's end):

func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
            
    WKInterfaceDevice.current().play(.start)
    
    print("message test workout")

}

I get a play sound and the printout message: "message test workout" when Apple Watch is on, but when Apple Watch's screen is off, the WatchOS app receives no signal. What code can I write from iOS app's end (Or anything else I can do from WatchOS app's end) to wake up the WatchOS app?

question from:https://stackoverflow.com/questions/65945620/why-can-my-apple-watch-os-app-receive-message-from-my-ios-app-only-when-it-is-ac

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should not call sendMessage straight after activate - The session may not (and probably won't) be active.

You need to wait until you get the activationDidCompleteWith delegate callback and then you can attempt communication.

Before attempting to send data you should check that the session state is .active and reactivate the session if it is no longer active.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...