0

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?

Victor
  • 222
  • 1
  • 6
  • 15
  • It's not clear from your question, what you are expecting to see. In any case, when calling indexSearchableItems, if you set searchableItem.identifier to some unique value, you can retrieve this value later from userActivity.userInfo?["kCSSearchableItemActivityIdentifier"]. Activity type of "com.apple.corespotlightitem" is correct and is what is expected. – Dale Jul 24 '18 at 01:49

1 Answers1

2

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
    }
}
Paulw11
  • 108,386
  • 14
  • 159
  • 186
  • Oh god, that pyramid of doom. User the comma operator, optional chaining and `Optional.map`/`Optional.flatMap`! – Alexander Jul 24 '18 at 02:00
  • That was it! I did not understand it properly and was treating both Core Spotlight and userActivity equally. Thank you! – Victor Jul 27 '18 at 23:34