我正在尝试使用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,我可以使用它来获得更好的搜索速度?
答案 0 :(得分:0)
在另一个操作队列中执行该作业,以便搜索不会冻结UI,并且如果您不希望查询占用所有CPU,则设置低质量的服务:
let queue = OperationQueue()
queue.qualityOfService = .background // If you want to speed up the query,
// try to set a higher QoS value
query.queue = queue