An Apple Watch app is capable of communicating with its parent iOS app. Developers can take advantage of this feature and bypass the limitation of a watch app by performing long-running, complex tasks on the iOS app and passing the data back to the Watch app. Read on to find out how.
Before you start the tutorial, make sure you have set up an Xcode project with a WatchKit app target. I assume that you are familiar with working with Xcode and Swift.
1. Open the Interface.storyboard file which is under the WatchKit App target, add a button to the initial view, and then connect the button to an action in code. In this example, I have named the action buttonPressed. Do not worry about the code inside it just yet.
2. Inside the buttonPressed action, add the following code:
We are passing a dictionary containing one item from the Watch app to the iOS app. The reply closure is called when there is data being sent back from the iOS app. You can set it to nil if this is one-way communication. Inside the closure, we are just checking to see if the data inside the dictionary is of type String, and then we print out the message.
3. Go to the AppDelegate.swift file, and add the following code to the bottom of the file. Please note that part of the handleWatchKitExtensionRequest function is excluded from the screenshot and that the function only works inside the AppDelegate file.
Inside this function, you can do any task you want. The data from the Watch app side can be extracted from the userInfo dictionary. In addition, you can send data back to the Watch app by setting the reply dictionary as I have demonstrated in the screenshot above.
4. Run the WatchKit App scheme, press the button in the watch app, and observe the results. If everything works, you will see Hello from Tech-Recipes in the debug panel.