首页 文章

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

提问于
浏览
3

我使用以下库来生成推送通知 .

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'的alert中的数据?

我尝试访问变量,但我不断收到错误,因为我不确定我应该如何访问它,并且在任何教程中找不到关于此主题的任何文档 .

4 回答

  • 1

    我认为这是一种更安全的方式来做约瑟夫发现的方式 .

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

    我渴望你试着找到一种避免使用力展开的方法 . 当您执行以下操作时:

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

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

    func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {
    
        do {
            let notification = try MTNotificationBuilder.build(from: data)
            print(notification.alert)
        } catch let error {
            print(error)
        }
    }
    
  • 2

    好的,我找到了答案 . 你这样做如下 .

    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
    

    如果有人有更安全的答案我会感谢他们编辑或发布它 .

  • 0

    确保在项目'功能'中打开'背景模式'并选中'远程通知' . 在AppDelegate类中添加以下方法 . 此方法将在提交通知时致电 .

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

相关问题