Wandering Mobile

Sharing Data With Handoff in iOS 8 and Xamarin

Handoff is a feature in iOS 8 that really gets me excited, it is a feature that gives a user the feeling that something magical just happened. Without any effort on the users part state is passed from one device to another enabling them to carry on where they left off. If i did not know any better i would honestly believe this could only be attributed to pure magic. Well, we do know better so let’s get onto how we build this into our own Xamarin apps.

Project Setup

To begin we need to add a new entry into the info.plist, they key is NSUserActivityTypes with and array as the value. you can the add a reverse domain url for each activity type you wish to be shared between apps.

Sharing Data

In our view controller we are now able to setup our state data which can be shared to other devices when in range. To do this we use the NSUserActivity class which is available through the UserActivity property on all UIResponder elements which most things in your view hierarchy derive from. We create the UserActivity we instantiate it by passing in the activity type like so:

To set the state we wish to share we only have to override the UpdateUserActivityState method which again resides on UIResponder. This method is called periodically by the OS but can be requested by setting the NeedsSave flag to true on the UserActivity object. Ideally we should only update the state in this method as prior to being called the OS will clean out the UserInfo dictionary;

In our AppDelegate we have two touch points to consider, overriding WillContinueUserActivity gives us the chance to decide if we are able to continue the incoming activity. If this is something the app can handle we can show the user a loading spinner while the activity is populated.

Secondly we must override ContinueUserActiviy, this gives us access to the fully populated user activity object and a completion handler which accepts an array of NSObject. We use this completion handler to pass in all of the UI elements or view controllers wish to handle the activity which has been passed. These will then have RestoreUserActivityState called on them.