Content indexed through CSSearchableIndex.default().indexSearchableItems()
is no longer searchable from Spotlight.
I created a very small app to demonstrate this. CSSearchableIndex.default().indexSearchableItems()
returned no error, yet the result can't be found.
import CoreSpotlight
import SwiftUI
@main
struct testspotlightApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.onContinueUserActivity(CSSearchableItemActionType, perform: handleSpotlight)
}
}
func handleSpotlight(_ userActivity: NSUserActivity) {
print("Found \(userActivity.userInfo?.debugDescription ?? "nothing")")
}
}
import CoreSpotlight
import SwiftUI
struct ContentView: View {
@State var result = ""
var body: some View {
VStack {
Text("Hello!")
Button {
let attribute = CSSearchableItemAttributeSet(contentType: .text)
attribute.title = "a page title"
attribute.contentDescription = "hello this is a page"
attribute.keywords = ["search", "this", "page", "title"]
let item = CSSearchableItem(
uniqueIdentifier: "12345", domainIdentifier: "com.test", attributeSet: attribute)
CSSearchableIndex.default().indexSearchableItems([item]) { error in
if let error {
result = "Failed to index: \(error.localizedDescription)"
} else {
result = "Successefully indexed to spotlight. Try searching 'a page title'"
}
}
} label: {
Text("Index a page").font(.title)
}
Text(result).multilineTextAlignment(.center)
}
.padding()
}
}
Has anyone else seen the same issue?
I finally figured out a way to fix it.
Previously when we create CSSearchableItemAttributeSet
when only set its title
property. Now with iOS 17, we also need to set displayName
property in order for the item to show up.
The code will look like this:
let attribute = CSSearchableItemAttributeSet(contentType: .item)
attribute.title = title
attribute.displayName = title // this is the line that's not required before iOS 17, but necessary now
let item = CSSearchableItem(uniqueIdentifier: id, domainIdentifier: nil, attributeSet: attribute)
CSSearchableIndex.default().indexSearchableItems([item])