iosswiftuispotlightnsuseractivity

Open specific view onContinueUserActivity


I am implementing spotlight search in my CoreData app. Indexing works fine, and when I click on the search result, my app opens in the main view. I have added this to my AppView:

import CoreSpotlight
import SwiftUI

struct AppView: View {
    var body: some View {
        
        // main view implementation

        }
        .onContinueUserActivity(CSSearchableItemActionType) { activity in
            continueActivity(activity)
        }
    }

    func continueActivity(_ activity: NSUserActivity) {
       if let id = userActivity.userInfo?[CSSearchableItemActivityIdentifier] as? String {
           // open detail view for the selected item
       }
   }
}

I don't want to open the main view but a detail view with the info of the selected item.

How can I do this?


Solution

  • This is the solution I came up with. First I get the actual NSManagedObject (an Entry), and then I append it to myNavigationPath.

    I hope it is helpful for others.

    func continueActivity(_ userActivity: NSUserActivity) {
        if let id = userActivity.userInfo?[CSSearchableItemActivityIdentifier] as? String {
            if let entry = coreDataController.entryFromObjectID(id) {
                myNavigationPath = .init()
                myNavigationPath.append(entry)
            }
        }
    }
    

    In my CoreDataController:

    func entryFromObjectID(_ id: String) -> Entry? {
        if let url = URL(string: id), let objectID = myPersistentStoreCoordinator.managedObjectID(forURIRepresentation: url) {
             if let entry = container.viewContext.object(with: objectID) as? Entry {
                return entry
             }
        }
    
        return nil
    }