How to use Handoff in your WatchKit app
(Originally published at FiveMinuteWatchKit.com, before the release of watchOS 2)
Considered by many to be an optional feature in their iOS/OSX apps, I believe Handoff will play an integral role in our WatchKit apps.
Need the user to sign in before they can use your Watch app? Handoff. Want to present content a big too long for the Watch? Handoff. Need specific OS-level permissions for your Watch app? Asking the user to Handoff to this phone and pop open an interface specifically asking for/setting those permissions up. When I see developers complain about WatchKit’s limitations, 99% of the time I think their problems could be easily solved by handing off to the iPhone and presenting custom UI.
Let’s take a look at how to implement it.
Give me your hand
To broadcast your app’s current activity, simply call updateUserActivity:userInfo:webpageURL: any time during the execution of your WKInterfaceController’s code. You should not create an NSUserActivityobject, as you would on iOS or OSX.
The updateUserActivity parameter requires an NSString describing the type of activity you’d like to broadcast in reverse-DNS format, by convention. It cannot be nil or an empty string.
userInfo expects an NSDictionary, as you might expect. This is where you can send along any data or state information the iPhone might need to pick up what the user is doing on the Watch. The contents of userInfo must be one of the following types: NSArray, NSData, NSDate, NSDictionary, NSNull, NSNumber, NSSet, or NSString.
Finally, you can optionally specify webpageURL to let the receiving iPhone continue your activity in Safari. Any URL scheme other than http or https throws an exception.
An activity will be broadcasted until the OS decides to kill it, you call updateUserActivity:userInfo:webpageURL: with a new activity, or call invalidateUserActivity to manually invalidate it.
Glances & Notifications
It isn’t obvious as first, but you can also call updateUserActivity:userInfo:webpageURL: from your Glance and custom notification interfaces. If you specify an activity that is recognized by the phone, it will allow the user to continue it there. But you can also “continue” the activity in your WatchKit app.
When your app is launched from a Glance or custom notification interface, any activity broadcasted from those interfaces will be passed to your root interface controller in the handleUserActivity: method.
If your app uses a page-based interface, handleUserActivity: will be called for each controller that is part of the initial interface. You don’t need to register the activity type in your WatchKit app for this to work. When overriding this method, don’t call super.
As usual, the iOS simulator does not support testing Handoff. Unless you have received an invite to one of the developer labs and can test on actual hardware, you’ll have to hope for the best or wait for the Watch to be released.