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

How to get timestamp of pushnotification in Swift?

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

我正在获取类似

的数据
   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 对象之外。

请检查一下 -> Apple Documentation


然后你需要解析它

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