Luc*_*ner 2 uikit apple-push-notifications ios swift
您好,我正在尝试快速读取推送通知的标题或正文变量。出于测试目的,我创建了一个 .apns 文件,并使用 xcrun 运行该文件
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" ]
}
Run Code Online (Sandbox Code Playgroud)
这是我用于推送通知按下的功能。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()
}
Run Code Online (Sandbox Code Playgroud)
用户信息的输出:
[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
)
,
Run Code Online (Sandbox Code Playgroud)
您可以使用以下代码从字典中提取标题和正文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")
Run Code Online (Sandbox Code Playgroud)
更新:如果您想用于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?
}
Run Code Online (Sandbox Code Playgroud)
然后,您必须使用将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)
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5016 次 |
最近记录: |