首页 > 解决方案 > UNNotificationContent userInfo 在处理响应时为空,但在发出请求时正确

问题描述

我正在构建一个桌面可可应用程序。当用户单击按钮时,如果成功下载资源,应用程序会向用户发送本地通知。当用户单击通知时,我想打开下载资源源的 URL。我正在尝试使用整数键将 URL 存储在userInfo字典中。UNMutableNotificationContent

我可以看到在添加通知请求之前内容就在那里:[AnyHashable(0): "https://stackoverflow.com/questions/ask"]但是在委托的处理程序中它是空的:[:]

// helper method to create the notification
func notify(userInfo: [AnyHashable : Any] = [:]) {
  let uid = UUID().uuidString
  let content = UNMutableNotificationContent()
  content.title = self.title
  content.userInfo = userInfo
  content.sound = UNNotificationSound.default
  print("add notification userInfo \(content.userInfo)")
  let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
  let request = UNNotificationRequest(identifier: uid, content: content, trigger: trigger)
  center.add(request) { (error) in
    print("add notification error \(error)")
  }
}

// notification click handler
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
  print("recieved notification userInfo: \(response.notification.request.content.userInfo)")
}

这是唯一创建通知的地方,我已经验证了请求identifiers匹配。

notify() 调用者示例

if let url = URL(string: "https://stackoverflow.com/questions/ask") {
  notificationDelegate.notify(userInfo: [0: url.absoluteString])                    
}

标签: swiftmacoscocoausernotifications

解决方案


UNNotificationContent的属性文档userInfo说明键必须是属性列表类型。这意味着它们必须是可直接存储在属性列表中的简短类型列表之一。此列表中的类似标量类型包括NSNumberNSStringNSDate.

据我所知,Int 0您用作键的字面 Swift应该NSNumber自动桥接,因此作为键是合法的。似乎这没有发生。

您将不得不直接使用其中一种 plist 类型。如果你想要一个数字作为键,0 as NSNumber应该可以工作(希望如此?),或者NSNumber(value: 0). 更常见的是,我认为键是字符串。

我认为这值得一提,特别是因为 SwiftString显然正确且自动地桥接的(到NSString)。(ObjC 方面的一个例外让我们知道字典无法编码,而不是无声消失,也很好......)


推荐阅读