2

我正在尝试使用 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 来提高搜索速度?

4

1 回答 1

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
于 2017-11-08T20:08:14.340 回答