如何在 Swift 中获取推送通知的时间戳?



我正在尝试获取推送通知数据。我能够获得标题和正文,但我也在尝试获取时间戳。

我正在获得这样的数据

func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print full message.
guard
let aps = userInfo[AnyHashable("aps")] as? NSDictionary,
let alert = aps["alert"] as? NSDictionary,
let body = alert["body"] as? String,
let title = alert["title"] as? String
else {
// handle any error here
return
}
print("Title: (title) nBody:(body)")
completionHandler()
}

有没有办法在推送通知有效负载本身或通过任何其他方式获取时间戳?

您应该将自定义timestamp数据添加到Push Notification的有效负载中。

通常有效载荷如下所示;

{
"aps":{
"alert":{
"title":"Hello",
"body":"How are you?"
},
"badge":0,
"sound":"default"
}
}

如果要将自定义字段添加到有效负载中,它应该看起来像 ->

{
"aps":{
"alert":{
"title":"Hello",
"body":"How are you?"
},
"badge":0,
"sound":"default"
},
"timestamp": "1590736069"
}

自定义字段必须位于对象外部aps

请查看此内容 -> 苹果文档


然后你需要解析它

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print full message.
guard
let aps = userInfo["aps"] as? NSDictionary,
let alert = aps["alert"] as? NSDictionary,
let body = alert["body"] as? String,
let title = alert["title"] as? String,
let timestamp = userInfo["timestamp"] as? String
else {
// handle any error here
return
}
print("Title: (title) nBody:(body)")
print("Timestamp is: (timestamp)")
completionHandler()
}

注意:无需使用AnyHashable即可使用字符串作为键。像userInfo["aps"]一样使用


获取当前日期的时间戳

如果您需要知道通知接收日期,您可以简单地获取当前Date的时间戳值,如下所示 ->

// Declare this in `didReceive` method and now you know the timestamp of notification received date
let timestamp = Date().timeIntervalSince1970

最新更新