如何阅读 swift 中推送通知的标题或 body?

How to read title or body of a push notification in swift?

您好,我正在尝试读取 swift 中推送通知的标题或 body 变量。出于测试目的,我创建了一个 .apns 文件,我 运行 和 xc运行

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 是完整的消息,它 returns 是此代码下方的输出。现在我需要 .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 字典中提取 titlebody

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?
}

然后,您必须使用 JSONSerializationuserInfo 字典转换回 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)
}