Topics

#29: Handoff 👋

Topics

Handoff is part of Apple's Continuity system. It allows users to begin a task or activity on one device, then continue it on another one. It's actually extremely simple to implement, all you do is tell the system what the user is currently doing in your app, and the system handles the rest. Here it is in code:

class EditSpaceshipViewController: UIViewController {
  func createActivity() {
    let activity = NSUserActivity(
      activityType: "com.littlebites.spaceships"
    )

    activity.title = "Edit Spaceship"

    activity.addUserInfoEntriesFromDictionary([
      "spaceshipID" : spaceship.spaceshipID
    ])

    activity.becomeCurrent()
  }

  override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    createActivity()
  }
}

Now, if the user picks up another device the activity your app's icon will appear in the bottom left of the user's lock screen on iOS, or in the dock on OS X, and the user can continue where they left off. To wrap things up, we just need to implement two additional UIApplicationDelegate methods:

func application(application: UIApplication, willContinueUserActivityWithType userActivityType: String) -> Bool {

  return true
}

func application(application: UIApplication,  continueUserActivity userActivity: NSUserActivity,  restorationHandler: ([AnyObject]?) -> Void) -> Bool {

  // use the userActivity object to restore the state
  // needed for the user to continue what they were doing

  return true
}