swiftmacosmacos-high-sierracorespotlight

Unknown Error when adding an CSSearchableItem to Core Spotlight (MacOS)


I recently wanted to power the search in one of my projects with Core Spotlight. However, whenever I add an CSSearchableItem to the SearchIndex, I get an error in the completion handler with the description:

The operation couldn’t be completed. (CSIndexErrorDomain error -1.)

According to Apple's reference, the error code -1 refers to Unknown Error, which isn't exactly helpful. I added both CoreSpotlight and CoreServices frameworks to my app and I really have no idea of what I might have done wrong.

I put together a minimal example:

import Foundation
import CoreSpotlight

print("Start indexing...")
let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String)
attributeSet.title = "test element"
attributeSet.contentDescription = "This is a description."
attributeSet.keywords =  ["test1", "test2", "test3"]
let item = CSSearchableItem(uniqueIdentifier: "123455", domainIdentifier: "TestDomain", attributeSet: attributeSet)
var ready = false
CSSearchableIndex.default().indexSearchableItems([item]) { (error) in
    if error == nil {
        print("Success")
    } else {
        print(error?.localizedDescription)
    }
    ready = true
}
//Wait for the block to finish
while (ready == false) {
    sleep(1)
}
print("Finish indexing...")

I managed to compile Apple's example project for Core Spotlight from WWDC17, and it does in fact work without an error. However, I can't obtain the indexed items with the systemwide Spotlight search.

Does anyone have an idea what might be off? By the way, I'm running the latest High Sierra release.

[Edit] Just saw, that there is in fact someone else with this question. However, the question isn't answered yet: Error while using CoreSpotlight

[Edit2] After updating to 10.13.2, the behaviour changed. This piece of code put in a playground is working now; however, the very same code put in my app does still produce an error, it does contain more information though. Printing the error object results in:

Error Domain=CSIndexErrorDomain Code=-1003 "(null)" 
UserInfo={NSUnderlyingError=0x60000105f6e0 
{Error Domain=NSCocoaErrorDomain Code=4097 
"Couldn’t communicate with a helper application."}}

As it displays to me, this is clearly a bug in the framework, or what do you think about that?


Solution

  • With macOS 10.13, SIP and the App Sandbox seem to have become a little more strict. After a lot of digging to get this work, here's what I did, and should work for others reading this too:

    1. In Xcode, toggle the "App Sandbox" capability for your target in which your CoreSpotlight code runs. If this is in a framework, it needs to be the hosting application's target. This shouldn't be necessary for new projects (for details, see this bug report).
    2. Enable development signing for the application/binary which will run the CoreSpotlight code. In my case, it was the test host.