首页 > 解决方案 > 如何快速阅读推送通知的标题或正文?

问题描述

您好,我正在尝试快速读取推送通知的标题或正文变量。出于测试目的,我创建了一个使用 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
)
,

标签: iosswiftuikitapple-push-notifications

解决方案


您可以使用以下代码从字典中提取标题正文: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)
}

推荐阅读