I am performing a NSMetadataQuery and I am getting all the URL for both Files and Directories.
func initSearchQuery(){
print("\(logClassName): initSearchQuery")
searchQuery.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]
let searchPredicate = NSPredicate.init(format: "%K like '*'", argumentArray: [NSMetadataItemFSNameKey])
searchQuery.predicate = searchPredicate
NotificationCenter.default.addObserver(self, selector: #selector(updateDataWithNotification), name: NSNotification.Name.NSMetadataQueryDidFinishGathering, object: searchQuery)
NotificationCenter.default.addObserver(self, selector: #selector(updateDataWithNotification), name: NSNotification.Name.NSMetadataQueryDidUpdate, object: searchQuery)
searchQuery.enableUpdates()
searchQuery.start()
}
Is there a way to do a predicate which would give only the URL's for the directory?
After some research I have finally resolved my problem.
Let's assume that we have the path for the iCloud folder
var iCloudUrl = fileManager.url(forUbiquityContainerIdentifier: nil)
iCloudUrl = iCloudUrl.appendingPathComponent("Documents")
And now we want to perform a NSMetadataQuery for folder1 inside the iCloud Documents folder.
We could access the content by declaring a NSPredicate like that:
let searchPredicate = NSPredicate.init(format: "%K BEGINSWITH %@", argumentArray: [NSMetadataItemPathKey,iCloudUrl.appendingPathComponent("Folder1").path])
It will return all the URL's for the folder, files and Subfolders.
1) If we just want to get the the files then the NSPredicate will look like that
let searchPredicate = NSPredicate.init(format: "%K BEGINSWITH %@ && NOT %K.pathExtension = ''", argumentArray: [NSMetadataItemPathKey,iCloudUrl.appendingPathComponent("Folder1").path,NSMetadataItemFSNameKey])
2) If we want to count how many folders and subfolder it has then
let searchPredicate = NSPredicate.init(format: "%K BEGINSWITH %@ && %K.pathExtension = ''", argumentArray: [NSMetadataItemPathKey,iCloudUrl.appendingPathComponent("Folder1").path,NSMetadataItemFSNameKey])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With