简体   繁体   English

如何使用NSMetadataQuery改进对iCloud Drive文件夹的搜索?

[英]How can I improve searching an iCloud Drive folder using NSMetadataQuery?

I'm trying to list the contents of a specific folder in iCloud Drive using NSMetadataQuery: 我正在尝试使用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 has all the items I'm expecting. query.results具有我期望的所有项目。 However, when the number of items in the app's cloud container is large (> 10K), it's taking a long time and is using ~100% of the cpu for close to a min. 但是,当应用程序的云容器中的项目数量很大(> 10K)时,这将花费很长时间,并且会占用约100%的cpu接近一分钟。

I tried to limit the search scope to just the test folder by setting the searchScopes and/or setting the searchItems : 我试图通过设置searchScopes和/或设置searchItems将搜索范围限制为仅测试文件夹:

query.searchScopes = ["\(container)/Documents/Test/"]
query.searchItems = ["\(container)/Documents/Test/"]

But didn't work. 但是没有用。 Please let me know if there is a way I can limit the search to a specific folder? 请让我知道是否可以将搜索范围限制为特定文件夹? Or if there is a different api I can use for better search speed? 还是如果我使用其他API可以提高搜索速度?

Do the job in another operation queue so that the search doesn't freeze the UI, and set a low quality of service if you don't want the query to take all the CPU: 在另一个操作队列中执行该作业,以使搜索不会冻结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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM