【发布时间】:2018-05-03 16:09:31
【问题描述】:
我最近想在我的一个项目中使用 Core Spotlight 为搜索提供动力。但是,每当我将 CSSearchableItem 添加到 SearchIndex 时,我都会在完成处理程序中收到错误说明:
The operation couldn’t be completed. (CSIndexErrorDomain error -1.)
根据Apple的参考,错误代码-1指的是Unknown Error,这并不完全有用。我在我的应用程序中添加了 CoreSpotlight 和 CoreServices 框架,但我真的不知道我可能做错了什么。
我整理了一个小例子:
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...")
我设法从 WWDC17 编译了 Apple 的 Core Spotlight 示例项目,它实际上可以正常工作而没有错误。但是,我无法通过系统范围的 Spotlight 搜索获取索引项目。
有人知道可能会发生什么吗?顺便说一句,我正在运行最新的 High Sierra 版本。
[编辑] 刚刚看到,其实还有人有这个问题。但是,这个问题还没有回答:Error while using CoreSpotlight
[Edit2] 更新到 10.13.2 后,行为发生了变化。放在操场上的这段代码现在可以工作了;但是,放在我的应用程序中的相同代码仍然会产生错误,但它确实包含更多信息。打印错误对象会导致:
Error Domain=CSIndexErrorDomain Code=-1003 "(null)"
UserInfo={NSUnderlyingError=0x60000105f6e0
{Error Domain=NSCocoaErrorDomain Code=4097
"Couldn’t communicate with a helper application."}}
正如它向我展示的那样,这显然是框架中的一个错误,或者您对此有何看法?
【问题讨论】:
-
你真的必须做
ready = false的事情吗?块内的所有代码在完成后都会执行,所以可能首先摆脱它,然后看看它是否有效。 -
另外:您是否在 AppDelegate 中包含
func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool方法和import CoreSpotlight? -
这个例子是一个 macOS 命令行应用程序,因此我需要这个等待的东西来防止应用程序在块完成之前被终止。您指的是 iOS 委托,是否有 macOS 等价物,是否真的有必要?我只想通过 CSSearchQuery 将索引用于我的应用内搜索。
-
'The ready = false' 的东西并不包含在实际的应用程序中,只是在演示中使其可运行。问题依然存在。
-
您可以在您的 macOS AppDelegate 中
import CoreSpotlight,我相信它是必需的。 AppDelegate 是您的应用程序中唯一基本上始终在运行的类/部分,您不能依赖 ViewControllers 来始终保持活动状态。我会导入框架并尝试 Swift 是否可以为您输入提示,因为我不确定 macOS 等价物是什么。
标签: swift macos macos-high-sierra corespotlight