In part 3 of this Apple Watch Development tutorial series we successfully created a complication for our Apple Watch application that displays data set in our iPhone application. Along the way we are learning about ClockKit, NSDate formatting and complications. In this tutorial we will update our applications so that the complication data is updated when the user changes our sabbatical start date in our iPhone app.
If you haven’t been with us from the start, the finished code from tutorial 3 is what we’re starting from.
First we need to alert the watch extension of the change and send it the new start date when it is saved in the iPhone app. We do this by calling the transferCurrentComplicationUserInfo method on the session and pass our new start date. Add the following lines to the end of the DisplayViewController’s saveSegue function in the iPhone app:
// update complication if session.watchAppInstalled { session.transferCurrentComplicationUserInfo(applicationDict) }
On the watch side we need to create a function to reload the data when session.didReceiveUserInfo is true. To do this, place these two new functions in the watch extension’s InterfaceController:
func session(session: WCSession, didReceiveUserInfo userInfo: [String : AnyObject]) { if let dateString = userInfo["dateKey"] as? String { // save new value to user defaults let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject(dateString, forKey: "dateKey") // reload complication data reloadComplications() } }
func reloadComplications() { let server = CLKComplicationServer.sharedInstance() guard let complications = server.activeComplications where complications.count > 0 else { return } for complication in complications { server.reloadTimelineForComplication(complication) } }
And now when you compile and test the apps your watch app will be updated automatically with new data when a new date is chosen and saved in the iPhone app.
The code for this Apple Watch development tutorial is on GitHub. If you are having trouble be sure to check out my article on Apple Watch Developer Tips and Tricks.
In this fourth and final part of this tutorial series we updated both apps so that data is refreshed in the Apple Watch app when it is changed in the iPhone app.
Check out the other posts in the series:
Apple Watch Development Tutorial (Part 1): Countdown App