簡體   English   中英

如何從推送通知響應 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;
}

所以我的問題是如何訪問警報中“正文”和“標題”的數據?

我嘗試訪問變量,但我不斷收到錯誤消息,因為我不確定應該如何訪問它,並且在任何教程中都找不到關於此主題的任何文檔。

我認為這是按照約瑟夫發現的方式進行的更安全的方法。

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)")

我希望您嘗試找到一種避免使用強制展開的方法。 當您執行以下操作時:

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

最后您需要做的就是調用 builder 函數並查看結果。 您可以嚴格並在任何情況下引入錯誤,使用也將有助於以后的可維護性。

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

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

確保您在項目“功能”中打開“背景模式”並選中“遠程通知”。 在 AppDelegate 類中添加以下方法。 此方法將在呈現通知時調用。

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

}

好吧,我找到了答案。 你像下面那樣做。

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

如果有人有更安全的答案,我會很感激他們編輯或發布它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM