I'm trying to list the contents of a specific folder in iCloud Drive using NSMetadataQuery:
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. 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.
I tried to limit the search scope to just the test folder by setting the searchScopes
and/or setting the 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?