I am implementing saving to iCloud Drive in my application. Right now I am testing the app on the simulator. I can save a file on to the iCloud Drive and it appears on the drive as expected. In my code, I have implemented NotificationCenter.default.addObserver. The startQuery() gets called with the application is made active. Here is the code sample:
@objc func startQuery()
{
stopQuery()
query = documentQuery()
print( "adding notifications" )
NotificationCenter.default.addObserver(self, selector: #selector(finishGatheringNotification(notifciations:)), name: NSNotification.Name.NSMetadataQueryDidFinishGathering, object:nil )
NotificationCenter.default.addObserver(self, selector: #selector(didUpdateNotification(notifciations:)), name: NSNotification.Name.NSMetadataQueryDidUpdate, object:nil )
query?.start()
}
@objc func stopQuery()
{
guard let query = self.query else{
return
}
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.NSMetadataQueryDidFinishGathering, object:nil )
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.NSMetadataQueryDidUpdate, object:nil )
query.stop()
self.query = nil
}
@objc func finishGatheringNotification( notifciations:NSNotification ){
print( "called finished gathering notification" )
processICloudFiles(notifciations: notifciations )
}
@objc func didUpdateNotification( notifciations:NSNotification ){
// This seems to be getting called non-stop
print( "called updated notification" )
processICloudFiles(notifciations: notifciations )
}
@objc func processICloudFiles( notifciations:NSNotification )
{
guard let query = query else{
return
}
query.disableUpdates()
var metaDataItems:[NSMetadataItem] = []
if let queryResults = query.results as? [NSMetadataItem]{
print( "query results:\(queryResults.count)")
for result in queryResults{
if let fileURL = result.value(forAttribute: NSMetadataItemURLKey ) as? NSURL{
print( "file found in iCloud:\(String(describing: fileURL.lastPathComponent))")
metaDataItems.append( result )
}
}
if metaDataItems.count > 0{
updateICloudFiles(metaDataItems: metaDataItems)
}
}
query.enableUpdates()
}
However, the selector for NSMetadataQueryDidUpdate is getting called no stop. I thought it was meant to get called only when the content of the iCloud disk changes.
Any suggestions.
Thanks
Reza
Try to deinitialize: