Skip to main content

How to continue an NSUserActivity in SwiftUI

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to continue an NSUserActivity in SwiftUI 관련

SwiftUI by Example

Back to Home

How to continue an NSUserActivity in SwiftUI | SwiftUI by Example

How to continue an NSUserActivity in SwiftUI

Updated for Xcode 15

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 {
    ContentView()
        .onContinueUserActivity(CSSearchableItemActionType, perform: handleSpotlight)
}

Of course, that’s just the bare bones of handling a user activity – you’ve detected the activity and your code has been run, but now you need to do the actual work of responding to the event somehow.

If you’re not sure where to start, you should probably make your handleSpotlight() set some shared state in your program that drives your UI, for example causing a detail view to present.

Similar solutions…
Answering the big question: should you learn SwiftUI, UIKit, or both? | SwiftUI by Example

Answering the big question: should you learn SwiftUI, UIKit, or both?
Frequently asked questions about SwiftUI | SwiftUI by Example

Frequently asked questions about SwiftUI
SwiftUI tips and tricks | SwiftUI by Example

SwiftUI tips and tricks
How to fix “Ambiguous reference to member 'buildBlock()'” | SwiftUI by Example

How to fix “Ambiguous reference to member 'buildBlock()'”
How to add Metal shaders to SwiftUI views using layer effects | SwiftUI by Example

How to add Metal shaders to SwiftUI views using layer effects

이찬희 (MarkiiimarK)
Never Stop Learning.