Ios 如何在swift中阅读推送通知的标题或正文?
您好,我正在尝试读取swift中推送通知的标题或主体变量。出于测试目的,我创建了一个.apns文件,并使用xcrun运行该文件 apns文件如下所示:Ios 如何在swift中阅读推送通知的标题或正文?,ios,swift,uikit,apple-push-notifications,Ios,Swift,Uikit,Apple Push Notifications,您好,我正在尝试读取swift中推送通知的标题或主体变量。出于测试目的,我创建了一个.apns文件,并使用xcrun运行该文件 apns文件如下所示: { "aps" : { "alert" : { "title" : "Dein Freund ist am Joggen", "body" : "Schick ihm
{
"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" ]
}
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是完整的消息,它返回此代码下面的输出。现在我需要.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()
}
userInfo的输出:
[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
)
,
[AnyHashable(“aps”):{
警报={
“动作锁定键”=播放;
body=“Schick ihm ne Anfrage bro”;
title=“Dein Freund Is am Joggen”;
};
徽章=5;
},AnyHashable(“acme2”):(
猛敲
天才
)
,
您可以使用以下代码从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
映射所有可能的字段,则要稍微困难一些
可以创建如下所示的模型:
{
"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" ]
}
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?
}
然后,您必须使用JSONSerialization
将userInfo
字典转换回Data
,最后使用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)
}
这正是我要找的