swift - 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])
}
解决方案
UNNotificationContent
的属性文档userInfo
说明键必须是属性列表类型。这意味着它们必须是可直接存储在属性列表中的简短类型列表之一。此列表中的类似标量类型包括NSNumber
、NSString
和NSDate
.
据我所知,Int
0
您用作键的字面 Swift应该NSNumber
自动桥接,因此作为键是合法的。似乎这没有发生。
您将不得不直接使用其中一种 plist 类型。如果你想要一个数字作为键,0 as NSNumber
应该可以工作(希望如此?),或者NSNumber(value: 0)
. 更常见的是,我认为键是字符串。
我认为这值得一提,特别是因为 SwiftString
显然是正确且自动地桥接的(到NSString
)。(ObjC 方面的一个例外让我们知道字典无法编码,而不是无声消失,也很好......)
推荐阅读
- javascript - 如何在 Angular 4 中设置表单值?
- javascript - 在 jquery 中的按钮单击中启用特定验证器
- bash - Bash 脚本打印输出两次
- c# - 如何使用来自给定键的 Linq Lambda 解析 XML 文件
- java - CollapsingToolBar 不起作用后添加 ScrollView
- javascript - 在 jQuery 中,如何替换文档的正文并仍然让 JavaScript 触发?
- spring - 在我导入 Hybris 项目后,Eclipse 无法正常运行(f3、ctrl+space、通过 ctrl 打开实现、编译错误)。
- jsf - Primefaces 树节点可拖动到子节点
- c++ - C++ Lambda,捕获子句如何深入
- python - 如何将字符串拆分到多个文件夹?