我正在我的应用程序中实现保存到 iCloud Drive。现在我正在模拟器上测试应用程序。我可以将文件保存到 iCloud Drive,它会按预期显示在驱动器上。在我的代码中,我实现了 NotificationCenter.default.addObserver。应用程序激活时调用 startQuery()。这是代码示例:
@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()
}
但是,NSMetadataQueryDidUpdate 的选择器被称为 no stop。我认为它只是在 iCloud 磁盘的内容发生变化时才会被调用。
有什么建议么。
谢谢礼
萨