Sub topic 12
For developers: adopting Handoff with NSUserActivity
This chapter is for developers who want their own app to appear in Handoff. It assumes you can build a basic iOS or macOS app in Swift, you know what a bundle identifier and an Info.plist are, and you have read the earlier chapters on how Handoff behaves for users. You also need two physical devices, such as an iPhone and a Mac, signed in to the same Apple Account with Handoff turned on.
The model: an activity is a small description of state
Handoff does not move your app's window or process between devices. It moves a small description of what the user is doing. Your app on device A publishes that description. Device B shows an icon for it, and when the user picks the icon, device B launches your app and passes the description to it. Your code on device B rebuilds the screen from that description.
The description is an NSUserActivity object. Its main parts are:
| Property | Purpose |
|---|---|
| `activityType` | A reverse-DNS string that names the kind of activity, such as `com.example.notes.viewing-note`. |
| `title` | A human-readable label used by the system. |
| `userInfo` | A dictionary holding the state needed to resume, such as a note identifier. |
| `isEligibleForHandoff` | Whether this activity may be offered on other devices. |
| `webpageURL` | An optional web address, used as a fallback when no native app can handle the activity. |
| `requiredUserInfoKeys` | Keys that must be present in `userInfo` when the activity is continued. |
An activity is only offered while it is current. Calling becomeCurrent() marks it current. Invalidating it, or letting its owner be deallocated, stops the offer.
Step 1: declare the activity type in Info.plist
The receiving app must list every activity type it can continue under the NSUserActivityTypes key. If the type is missing, the receiving device does not offer it. This is the most common reason for an activity that never appears.
<key>NSUserActivityTypes</key>
<array>
<string>com.example.notes.viewing-note</string>
</array>Add the same key to both the iOS and the macOS targets if you want Handoff in both directions. Use the same string in both apps.
Step 2: publish the activity from the sending app
The following UIKit code creates the activity when a note screen appears and makes it current. It uses the view controller's built-in userActivity property, so UIKit manages the lifetime for you.
import UIKit
final class NoteViewController: UIViewController {
var noteID = "42"
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let activity = NSUserActivity(activityType: "com.example.notes.viewing-note")
activity.title = "Viewing a note"
activity.userInfo = ["noteID": noteID]
activity.isEligibleForHandoff = true
userActivity = activity
activity.becomeCurrent()
}
}Assigning the activity to userActivity on a view controller ties it to that screen. When the screen goes away, UIKit invalidates the activity.
In SwiftUI, the userActivity view modifier does the same job and ties the activity to the view's presence on screen:
import SwiftUI
struct NoteView: View {
let noteID: String
var body: some View {
Text("Note \(noteID)")
.userActivity("com.example.notes.viewing-note") { activity in
activity.title = "Viewing a note"
activity.userInfo = ["noteID": noteID]
activity.isEligibleForHandoff = true
}
}
}The modifier's closure runs whenever the activity is created or needs refreshing. It also accepts an isActive argument if you want to publish the activity only under some condition.
Step 3: receive and restore the activity
On the receiving device, the system launches your app and hands over the activity. Your code reads userInfo and shows the right screen. In SwiftUI, use onContinueUserActivity:
import SwiftUI
@main
struct NotesApp: App {
@State private var selectedNoteID: String?
var body: some Scene {
WindowGroup {
ContentView(selectedNoteID: selectedNoteID)
.onContinueUserActivity("com.example.notes.viewing-note") { activity in
if let id = activity.userInfo?["noteID"] as? String {
selectedNoteID = id
}
}
}
}
}
struct ContentView: View {
let selectedNoteID: String?
var body: some View {
if let id = selectedNoteID {
NoteView(noteID: id)
} else {
Text("Choose a note")
}
}
}In a UIKit app that uses scenes, implement the scene delegate method scene(_:continue:). In an app without scenes, implement application(_:continue:restorationHandler:) in the app delegate and return true if you handled the activity. Both receive the same NSUserActivity with the userInfo the sender published.
Treat userInfo as untrusted input. Check that the keys exist and that the values have the types you expect. Also check that the identifier refers to something that exists on this device. The note might have been deleted, or it might not have synced yet.
Failures during continuation
If the system cannot deliver the activity, for example because the transfer is interrupted, UIKit calls application(_:didFailToContinueUserActivityWithType:error:) on the app delegate. Log the error and show a neutral screen instead of leaving the user on a blank launch state.
What belongs in userInfo
Handoff payloads are small. Apple documents a limit of about 4 KB for userInfo. Keep these rules in mind:
- Store identifiers and small pieces of position state, such as a note ID, a scroll offset, or a selected tab. Do not store document bodies or images.
- Use property-list types: strings, numbers, dates, URLs, arrays, dictionaries, and
Dataof small size. - Make the identifier resolvable on the receiving side. If the data lives in iCloud, CloudKit, or your own server, the receiving app looks it up by ID.
- Version your payload. Add a key such as
"schema": 1so that an older app version can ignore a newer payload instead of crashing.
If you truly need to transfer a large amount of data, set supportsContinuationStreams to true on the activity. The receiving app can then call getContinuationStreams to open input and output streams to the sending app. This only works while both devices stay in range, so it suits live content more than saved documents.
Updating the activity as state changes
A user may scroll or switch tabs after the activity is published. You have two options for keeping userInfo current:
- Update
userInfodirectly and callbecomeCurrent()again, or useaddUserInfoEntries(from:)for a partial update. - Set
needsSave = trueon the activity. The system then callsuserActivityWillSave(_:)on the view controller, which is the right place to write the latest values intouserInfojust before they are sent.
The second approach avoids doing work on every change. Mark the activity dirty when state changes, and the system asks for the real values only when it needs to send them.
Web fallback
If the receiving device does not have your app, you can still let the user continue in a browser. Set webpageURL to an https address that shows the same content:
import Foundation
func makeActivity(noteID: String) -> NSUserActivity {
let activity = NSUserActivity(activityType: "com.example.notes.viewing-note")
activity.title = "Viewing a note"
activity.userInfo = ["noteID": noteID]
activity.isEligibleForHandoff = true
activity.webpageURL = URL(string: "https://notes.example.com/n/\(noteID)")
return activity
}When both a native app and a web URL exist, the native app wins if it is installed and its team matches. Otherwise the system opens the URL in the default browser.
Testing
Handoff relies on Bluetooth Low Energy and the same Apple Account on both devices. The iOS Simulator cannot take part, so test on physical hardware. A reliable test routine is:
- Install the iOS build on the iPhone and the macOS build on the Mac, both signed with the same team.
- Confirm that Handoff is on for both devices and that Bluetooth and Wi-Fi are enabled.
- Open the note screen on the iPhone. Keep the screen on and the app in the foreground.
- Look for your app's icon at the left end of the Mac's Dock, or look for it in the app switcher on a second iPhone or iPad.
- Click the icon. Check that the Mac app launches and shows note 42.
To debug, put a print call or a breakpoint in the continuation handler, and log in the sender when becomeCurrent() is called. If the sender logs but no icon appears, the problem is in discovery or configuration. If the icon appears and the app launches but shows the wrong screen, the problem is in your restore code.
Common mistakes
| Symptom | Likely cause |
|---|---|
| No icon ever appears on the receiving device | The activity type is missing from `NSUserActivityTypes`, or the two apps use different teams. |
| Icon appears, but app opens on its home screen | The continuation handler is not registered, or it does not match the activity type string exactly. |
| Activity disappears while the user is still on the screen | The activity was invalidated or released. Keep a strong reference or attach it to the view controller's `userActivity`. |
| Payload is dropped | `userInfo` is too large or contains a type that cannot be stored in a property list. |
| Works one way only | Only one target declares the activity type in its Info.plist. |
Check your understanding
Exercise
Your iPhone app publishes an activity with type com.example.notes.viewing-note and calls becomeCurrent(). The Mac app launches when the user clicks the Dock icon, but the Mac never offers the icon from the iPhone's activity when you start from a fresh install of a different Mac build. Name the first Info.plist key you would check in the Mac target and what it must contain.
Show answer
Check NSUserActivityTypes. It must be an array that includes the exact string com.example.notes.viewing-note. Without that entry the Mac app does not declare that it can continue this activity type, so the system will not offer it.
Exercise
A teammate stores the full text of a 40 KB note in userInfo so the receiving app does not need a network call. Why is this a poor design, and what should be stored instead?
Show answer
userInfo is limited to about 4 KB, so the payload will be dropped or fail. Store only the note's identifier, plus small state such as a cursor position, and have the receiving app load the full text from iCloud or the server. If live data really must be streamed, set supportsContinuationStreams and use continuation streams.
Exercise
You are testing in Xcode with the iOS Simulator and a Mac, and no Handoff icon ever appears. What is the problem with the test setup?
Show answer
The Simulator does not take part in Handoff. Handoff needs physical devices that use Bluetooth Low Energy and share an Apple Account. Test with a real iPhone and a Mac, both with Handoff, Bluetooth, and Wi-Fi turned on.