我正在尝试使用 NSMetadataQuery 列出 iCloud Drive 中特定文件夹的内容:
let query = NSMetadataQuery()
func listAllItemsInTheTestFolder() {
guard let container = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.path else {return}
NotificationCenter.default.addObserver(self, selector: #selector(didFinishGathering), name: .NSMetadataQueryDidFinishGathering, object: query)
query.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]
query.predicate = NSPredicate(format: "%K BEGINSWITH %@", NSMetadataItemPathKey, "\(container)/Documents/Test/")
query.start()
}
// The issue is that it's taking close to a min and a spike in cpu usage when there are more than 10K items in the container.
// Do note: The folder I'm interested in has less than five items.
@objc func didFinishGathering() {
query.stop()
NotificationCenter.default.removeObserver(self, name: .NSMetadataQueryDidFinishGathering, object: query)
let names = query.results.map{($0 as? NSMetadataItem)?.value(forAttribute: NSMetadataItemDisplayNameKey)}
print("Count: ", query.resultCount, "names: ", names) // Expected
}
query.results
有我期待的所有物品。但是,当应用程序的云容器中的项目数量很大(> 10K)时,它会花费很长时间并且使用约 100% 的 cpu 接近一分钟。
我试图通过设置searchScopes
和/或设置将搜索范围限制为测试文件夹searchItems
:
query.searchScopes = ["\(container)/Documents/Test/"]
query.searchItems = ["\(container)/Documents/Test/"]
但是没有用。请让我知道是否有办法将搜索限制到特定文件夹?或者,如果我可以使用不同的 api 来提高搜索速度?