ios - 如何快速阅读推送通知的标题或正文?
问题描述
您好,我正在尝试快速读取推送通知的标题或正文变量。出于测试目的,我创建了一个使用 xcrun 运行的 .apns 文件
apns 文件如下所示:
{
"aps" : {
"alert" : {
"title" : "Dein Freund ist am Joggen",
"body" : "Schick ihm ne Anfrage bro ",
"action-loc-key" : "PLAY"
},
"badge" : 5
},
"acme1" : "bar",
"acme2" : [ "bang", "whiz" ]
}
这是我用于推送通知的功能。Userinfo 是完整的消息,它返回此代码下方的输出。现在我需要 .title 或 .body 变量我怎样才能得到它们?
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
let application = UIApplication.shared
if(application.applicationState == .active){
//Prints the message when user tapped the notification bar when the app is in foreground
print(userInfo)
//Get the title of userInfo
}
if(application.applicationState == .inactive)
{
print("user tapped the notification bar when the app is in background")
}
completionHandler()
}
用户信息的输出:
[AnyHashable("aps"): {
alert = {
"action-loc-key" = PLAY;
body = "Schick ihm ne Anfrage bro ";
title = "Dein Freund ist am Joggen";
};
badge = 5;
}, AnyHashable("acme2"): <__NSArrayM 0x6000000105d0>(
bang,
whiz
)
,
解决方案
您可以使用以下代码从字典中提取标题和正文:userInfo
let aps = userInfo["aps"] as? [String: Any]
let alert = aps?["alert"] as? [String: String]
let title = alert?["title"]
let body = alert?["body"]
print(title ?? "nil")
print(body ?? "nil")
更新:如果你想用来Codable
映射所有可能的字段,它会稍微困难一些。
您可以像这样创建模型:
struct Payload: Decodable {
let aps: APS
let acme1: String?
let acme2: [String]?
}
struct APS: Decodable {
let alert: Alert
let badge: Int?
}
struct Alert: Decodable {
let title: String
let body: String?
let action: String?
}
然后,您必须将userInfo
字典转换回Data
,使用JSONSerialization
并最终使用以下方法解码数据JSONDecoder
:
let decoder = JSONDecoder()
do {
let data = try JSONSerialization.data(withJSONObject: userInfo)
let payload = try decoder.decode(Payload.self, from: data)
print(payload.aps.alert.title)
print(payload.aps.alert.body ?? "nil")
} catch {
print(error)
}
推荐阅读
- reactiveui - ReactiveUI WhenAnyValue
- mysql - 表空间文件./sys/sys_config.ibd的大小只有81920,至少应该是98304
- ruby-on-rails - 如何为来自 Rails 视图的日期设置时区
- c# - MVC 在 ViewModels 中使用 DTO 类
- firebase - Flutter Firebase 流中的 Where 子句
- erlang - 为什么 OTP 中的类型规范会重复参数名称?
- mongodb - Mongoose:如何自动删除数组中的旧条目?
- python - Trying to load certain form if user is authenticated and preload all the information in the database with the user credentials
- c - 处理指针时如何应对冲突类型错误?
- x86 - 现代 x86 CPU 使用什么缓存一致性解决方案?