gpt4 book ai didi

swift - 如何改进使用 NSMetadataQuery 搜索 iCloud Drive 文件夹?

转载 作者:行者123 更新时间:2023-11-28 07:59:05 26 4
gpt4 key购买 nike

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

最佳答案

在另一个操作队列中执行此作业,以便搜索不会卡住 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

关于swift - 如何改进使用 NSMetadataQuery 搜索 iCloud Drive 文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47188467/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com