【问题标题】:How can I improve searching an iCloud Drive folder using NSMetadataQuery?如何改进使用 NSMetadataQuery 搜索 iCloud Drive 文件夹?
【发布时间】:2018-04-21 15:46:30
【问题描述】:

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

【问题讨论】:

    标签: swift icloud-api icloud-drive nsmetadataquery


    【解决方案1】:

    在另一个操作队列中执行该工作,以便搜索不会冻结 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-14
      • 2011-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-04
      相关资源
      最近更新 更多