如何从推送通知响应中获取数据 Swift 3/iOS

How to get data from push notification response Swift 3/iOS

我正在使用以下库生成推送通知。

https://github.com/edamov/pushok

我收到了推送通知,但我不知道如何提取 Swift 中的响应 3.

这是我的。

// Push notification received
    func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {
        // Print notification payload data
        print("Push notification received: \(data)")

        let aps = data[AnyHashable("aps")]!

        print(aps)
    }

我可以创建推送通知并且控制台消息有效但打印出来...

Push notification received: [AnyHashable("samplekey"): samplevalue, AnyHashable("aps"): {
    alert =     {
        body = hey;
        title = "Hello!";
    };
    sound = default;
}]
{
    alert =     {
        body = hey;
        title = "Hello!";
    };
    sound = default;
}

所以我的问题是如何访问 'body' 和 'title' 警报中的数据?

我尝试访问这些变量,但我一直收到错误,因为我不确定我应该如何访问它,并且在任何教程中都找不到关于这个主题的任何文档。

好的,我找到了答案。你可以像下面那样做。

let aps = data[AnyHashable("aps")]! as! NSDictionary        
let alert = aps["alert"]! as! NSDictionary
let body = alert["body"] as! String
let title = alert["title"] as! String

如果有人有更安全的答案,我将不胜感激他们编辑或发布它。

我希望您能尝试找到一种避免使用强制展开的方法。当您执行以下操作时:

 let alert = aps["alert"]! as! NSDictionary
 let body = alert["body"] as! String
 let title = alert["title"] as! String

如果缺少上述任何值,应用程序将崩溃。

相反,首先让我们介绍一个通知模型。

class MTNotification {
    let alert: [String: AnyHashable]
    var title: String?
    var body: String?

    init(alert: [String: AnyHashable]) {
        self.alert = alert
    }
}

使用一些东西来跟踪处理原始通知数据时可能发生的错误。如果你让它符合 Error 协议就更好了。

enum MTError: Error {
    // Observe your transformation and extend error cases
    case missingProperty(id: String)
}

使用助手 class 不要污染应用委托,您可以在其中处理数据到通知的转换。

class MTNotificationBuilder {

     /// Build a notification from raw data
     ///
     /// - Parameter data: Classic notification payload, received from app delegate
     /// - Returns: customized MTNotification
     /// - Throws: error while building a valid MTNotification object
    static func build(from data: [AnyHashable : Any]) throws -> MTNotification {
        guard let aps = data["aps"] as? [String: AnyHashable] else {
            // Do some error handlig
            throw MTError.missingProperty(id: "aps")
        }

        guard let alert = aps["alert"] as? [String: AnyHashable] else {
            // Do some error handlig
            throw MTError.missingProperty(id: "aps")
        }

        let notification = MTNotification(alert: alert)
        // Assign values read as optionals from alert dictionary
        notification.title = alert["title"] as? String
        notification.body = alert["body"] as? String

        return notification
    } 
}

最后您需要做的就是调用构建器函数并查看结果。您可以严格并为任何情况引入错误,同时使用将有助于以后的可维护性。

func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {

    do {
        let notification = try MTNotificationBuilder.build(from: data)
        print(notification.alert)
    } catch let error {
        print(error)
    }
}

我认为这是 Joseph 发现的更安全的方法。

guard
    let aps = data[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)")

确保在项目 'capabilities' 中打开 'ON' 背景模式并选中 'Remote Notifications'。 在 AppDelegate class 中添加以下方法。此方法将在呈现通知时调用。

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        print(notification.request.content.userInfo)
        completionHandler([ .alert,.badge, .sound])

}