Warm tip: This article is reproduced from serverfault.com, please click

ios-如何快速阅读推送通知的标题或正文?

(ios - How to read title or body of a push notification in swift?)

发布于 2020-12-27 17:51:33

你好,我想快速读取我的推送通知的title或body变量。为了进行测试,我创建了一个.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" ]
}

这是我用于推送通知新闻的功能。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
)
,
Questioner
Lucas Goldner
Viewed
0
gcharita 2020-12-28 04:00:46

你可以使用以下代码字典中提取标题正文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字典转换DataJSONSerialization最后使用解码数据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)
}