gpt4 book ai didi

swift - NSNotification NSMetadataQueryDidUpdate 获取不间断的通知消息

转载 作者:行者123 更新时间:2023-11-30 11:57:31 24 4
gpt4 key购买 nike

我正在我的应用程序中实现保存到 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 的选择器被不停地调用。我认为它只在 iCloud 磁盘内容发生变化时才会被调用。
任何建议。
谢谢
礼萨

最佳答案

尝试取消初始化:

deinit {
NotificationCenter.default.removeObserver(self)
}

关于swift - NSNotification NSMetadataQueryDidUpdate 获取不间断的通知消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47640039/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com