How to use WatchConnectivity to send data from Watch to Phone — Part 2
When I wrote the first part of this article, I had been doing iOS Development for… well.. just about 4 months!
Nonetheless I was very excited about all the few little things I learned at the time, with the little experience I had.
Lately I had the chance to mess around with the Watch again, and had fun learning how to pass more complex data from Watch to Phone and viceversa. So, after almost 3 years, buckle up and let’s get started with part 2!
Let’s say you want to pass your own object from Watch to Phone.
- First let’s create our object.
In order to send it from one device to the other, however, since it doesn’t fall in the property list types, we have to pass it as Data and then convert it back to our object.
2. Once we have our encode and decode functions, we can send our dictionary from the InterfaceViewController with a simple button:
3. Now it’s time to receive what we sent! Let’s go in our ViewController, create an array of our bookmarks and setup the delegate methods to start populate it.
And that’s it!
Tips:
- The func sendMessage(_:replyHandler:errorHandler:) will also work in the Simulator while for example the transferUserInfo(_:) won’t
- Sometimes you might get the error: “Type ‘X’ does not conform to protocol ‘Encodable/Decodable’”. This article can help!
- Xcode 13.4 is the last version of Xcode that will let you create the WatchKit App and the WatchKit Extension targets, which was the only way I found to be able to send data (I am sure there is also a way true SwiftUI and watchOS 7.0, but I haven’t figured it out yet)
FULL CODE
Here’s 2 articles that helped me with this Watch Connectivity journey:
- Sending Data Between watchOS and iOS App Using Watch Connectivity
- Transfer custom objects between Apple Watch and iPhone with swift
Thank you for reading the article. Feel free to ask any question, correct any mistake & happy coding! 🍎