2

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?

Syzygy
  • 123
  • 2
  • 9

1 Answers1

0

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:

let queue = OperationQueue() 
queue.qualityOfService = .background // If you want to speed up the query,
                                     // try to set a higher QoS value 
query.queue = queue
Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187