分布式通知中心 - 如何在应用程序之间传递数据?



我已经构建了两个应用程序,"主"应用程序和支持它的Finder扩展。 使用分布式通知中心,我可以成功地在应用程序之间来回发布消息,并且注册的观察者事件按预期触发。

问题似乎是我无法随事件传递任何用户数据。所有文档都建议你可以传递一个NSDictionary[AnyHashable: Any]对象作为postNotificationName的一部分。

例如:发布消息看起来像这样...

let center: DistributedNotificationCenter = DistributedNotificationCenter.default()
center.postNotificationName(NSNotification.Name(name), object: nil, userInfo: mydata, deliverImmediately: true)

这是我的查找器扩展发送代码:

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 它是 nil,如果我查询 notification.object,它也是 nil。

我尝试了我能想到的一切,但我完全不知所措。

对于任何偶然发现这一点的人来说,事实证明,我能让它工作的唯一方法是将我自己的任何数据作为消息的一部分发布,就是将其包含在 postNotificationName 方法的 Object 属性中。 用户信息在进程边界上被完全忽略。

所以我将我自己的类 CacheEntry 序列化为一个字符串,发布它,然后在另一端解开包装。

所以像这样:

func sendMessage(name: String, data:CacheEntry( {

let message:String = createMessageData(messsagePayload: data)

let center: DistributedNotificationCenter = DistributedNotificationCenter.default()
center.postNotificationName(NSNotification.Name(name), object: message, userInfo: nil, deliverImmediately: true)
}

func createMessageData(messsagePayload:CacheEntry( -> String {

let encoder = JSONEncoder()
let data = try! encoder.encode(messsagePayload)

let messsagePayloadString = String(data: data, encoding: .utf8)!
return String(messsagePayloadString)
}

func reconstructEntry(messagePayload:String( -> CacheEntry {

let jsonData = messagePayload.data(using: .utf8)!
let messsagePayloadCacheEntry = try! JSONDecoder().decode(CacheEntry.self, from: jsonData)

return messsagePayloadCacheEntry
}
@objc func recievedMessage(notification:NSNotification){

NSLog ("Message Received from Application (notification.name)")

if notification.name.rawValue == "DSF-SetSyncState" {

NSLog ("Message Recieved from Application to set the sync icon")

let cEntry = reconstructEntry(messagePayload: notification.object as! String)
}

}

看起来沙盒应用程序不允许使用 userInfo 参数

重要

沙盒应用只有在不包含字典的情况下才能发送通知。如果发送应用程序位于应用程序沙盒中,则用户信息必须为零。

https://developer.apple.com/documentation/foundation/nsdistributednotificationcenter/1418360-postnotificationname

相关内容

最新更新