Morten Gustafsson
Morten Gustafsson

Reputation: 1899

Send a messages from App to watchOS in Swift

Is it possible to send a messages from my App to my watchOS extension, so I ex. can update my watch UI?

I'm using WKInterfaceController.openParentApplication to send information from the watch extension to the App. But how do I do the opposite way - From the App to the Watch extension?

Upvotes: 4

Views: 3607

Answers (2)

Abhishek Thapliyal
Abhishek Thapliyal

Reputation: 3708

Watch OS 4+

Updating @Philip Answer you need to do after setuping session

You need to use replyHandler Method to get data from iPhone to WatchOS App Extention like this

WCSession.default.sendMessageData(Data(), replyHandler: { (data) in
            let deviceId = String(data: data, encoding: .utf8)
            print("DEVICE ID : \(deviceId)")
            DataModel.shared.deviceId = deviceId
        }, errorHandler: nil)

This will be called from Watch App Extension as per your requirement.

In Main App Delegate you need to implement WatchKit Session Delegate

   // WATCH OS MESSAGE RECIEVE WITH REPLY HANDLER
    func session(_ session: WCSession, didReceiveMessageData messageData: Data, replyHandler: @escaping (Data) -> Void) {
        print("SESSION MESSSAGE DATA: \(messageData)")
        if let deviceId = UIDevice.current.identifierForVendor?.uuidString,
            let data = deviceId.data(using: .utf8) {
            print("REPLY HANDLER MESSSAGE DATA: \(data)")
            replyHandler(data)
        }
    }

In the replyHandler you can pass information in Data Format.

Upvotes: 3

Philip
Philip

Reputation: 2285

If you are developing for watchOS2 to can use WatchConnectivity. This give you several options to transfer data back and forth between your watch and iPhone.

If you want to send a message from the watch to the iPhone (when both are active) use interactive messaging. Read more about WatchConnectivity to understand the different ways to send data. I´ll give you a short code example.

You need to extend the WCSessionDelegate on both watch and iOS.

if (WCSession.isSupported()) {
     let session = WCSession.defaultSession()
     session.delegate = self 
     session.activateSession()
     
}

if (WCSession.defaultSession().reachable) {
    //This means the companion app is reachable
}

On your watch, this will send data.

let data = //This is the data you will send
WCSession.defaultSession().sendMessage(data,
       replyHandler: { ([String : AnyObject]) → Void in

       })
        errorHandler: { (NSError) → Void in

});

And on your iPhone to receive the data implement the delegate-method:

func session(_ session: WCSession,
    didReceiveMessage message: [String : AnyObject])

Upvotes: 3

Related Questions