iosswiftxcodecorespotlightnsuseractivity

NSUserActivity vs. Core Spotlight deep link


I am using both NSUserActivity and Core Spotlight to index content on my app. The reason I am using Core Spotlight is because I want to index this content before the user access (opens) it.

The problem I am facing is in the AppDelegate method: func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool

Basically userActivity ONLY contains the correct information when I do this in my viewController:

userActivity = myUserActivity

But it does not work if I do:

CSSearchableIndex.default().indexSearchableItems(searchableItems).

By using the second method (Core Spotlight) I can see all my results in spotlight search, but when I tap the item, I don't have any information in the AppDelegate method.

The worst part is this:

po userActivity.activityType "com.apple.corespotlightitem"

If I print the activityType, instead of getting my own, I get this one...

Any suggestions?


Solution

  • When your app is launched from a CoreSpotlight result you get a CSSearchableItemActionType.

    You need to handle this type of action by retrieving the CSSearchableItemActivityIdentifier - This value will match the identifier you provided for your searchable item when you submitted it to the index.

    Something like:

    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
        if userActivity.activityType == CSSearchableItemActionType {
            guard let selectedItem = userActivity.userInfo?[CSSearchableItemActivityIdentifier] as? String else {
                return
            }
            // Do something with selectedItem
        }
    }