我构建了两个应用程序:“主”应用程序和一个支持它的 Finder 扩展。使用分布式通知中心我可以成功地在应用程序之间来回发布消息,并且注册的观察者事件会按预期触发。
问题似乎是我无法通过该事件传递任何用户数据。所有文档都表明您可以通过NS词典 or [任何Hashable:任何]对象作为发布通知名称
例如:发布消息看起来像这样......
let center: DistributedNotificationCenter = DistributedNotificationCenter.default()
center.postNotificationName(NSNotification.Name(name), object: nil, userInfo: mydata, deliverImmediately: true)
这是我的 Finder 扩展发送代码:
var myInfo = [AnyHashable: Any]()
myInfo[AnyHashable("filename")] = "Test Data"
let center: DistributedNotificationCenter = DistributedNotificationCenter.default()
center.postNotificationName(NSNotification.Name("RequestSyncState"), object: nil, userInfo: myInfo, deliverImmediately: true)
主应用程序接收代码:
@objc func recievedMessage(notification:NSNotification){
NSLog ("Message Recieved from Finder Extension \(notification.name.rawValue)")
if notification.name.rawValue == "RequestSyncState" {
NSLog ("Message Recieved from Finder to determine the sync icon")
guard let userInfo = notification.userInfo else
{
return
}
guard let value = userInfo["Filename"] else
{
NSLog ("Message payload is empty")
return
}
NSLog ("Message payload is \(value)")
}
正如我所说,这些函数会触发并收到通知,但没有实际数据。如果我查询 notification.userInfo 它为零,如果我查询 notification.object 它也为零。
我尝试了我能想到的一切,但我完全不知所措。