BLACK FRIDAY: Save 50% on all books and bundles! >>

How to continue an NSUserActivity in SwiftUI

Paul Hudson    @twostraws   

Updated for Xcode 12.0

New in iOS 14

SwiftUI has a dedicated onContinueUserActivity() modifier that can catch a variety of NSUserActivity types – clicks from the web, launches from Spotlight or Siri, and more. Previously you might have handled this in your AppDelegate using something like application(_:continue:restorationHandler:), but SwiftUI’s approach is more fine-grained and lets us divide functionality more easily.

To implement this, first create a function that will accept an NSUserActivity. You don’t need to do this inside your App struct, but it would make sense to do so because you can then route it wherever you need in the rest of your program.

For example, this function checks to see whether we’re being passed in data from Spotlight, and if so pulls out the unique identifier so you can look it up in your data source:

func handleSpotlight(_ userActivity: NSUserActivity) {
    if let id = userActivity.userInfo?[CSSearchableItemActivityIdentifier] as? String {
        print("Found identifier \(id)")

Note: That doesn’t need to check the activityType property, because it will be filtered by SwiftUI in our next code.

Now you can attach that to your main app’s view by modifying your App struct like this:

WindowGroup {
        .onContinueUserActivity(CSSearchableItemActionType, perform: handleSpotlight)

Save 50% in my Black Friday sale.

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

Buy Pro Swift Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift (Vapor Edition) Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.0/5

Link copied to your pasteboard.