【问题标题】:FCM UserInfo, how to drill-down it's value?FCM UserInfo,如何深入挖掘它的价值?
【发布时间】:2018-03-16 12:39:09
【问题描述】:

当我收到来自 FCM 的消息时,我可以打印它的所有内容直到这一点

if let message = userInfo[AnyHashable("message")]  {
                        print(message)
                    }

消息正文包含类似 => {"sent_at":1521203039,"sender":{"name":"sender_name","id":923},"id":1589,"body":"sdfsadf sdfdfsadf"}的字符串

消息类型是任何,我希望从这个消息对象中读取名称和正文。

func handleNotification(_ userInfo: [AnyHashable: Any]) -> Void {
            if let notificationType = userInfo["job_type"] as? String {
                if notificationType == "mobilock_plus.message" {
                    //broadcast message recieved
                    if let message = userInfo[AnyHashable("message")]  {
                        print(message)
                        //TODO :- read name and body of message object.
                    }
                }
            }
        }

【问题讨论】:

标签: ios swift firebase apple-push-notifications firebase-cloud-messaging


【解决方案1】:

我认为您正在查看的是将字符串转换为 Json 对象。

下面的答案可以帮你做到

How to convert a JSON string to a dictionary?

【讨论】:

  • 这应该是评论!!
【解决方案2】:

所以在@Harsh 回答的帮助下,我能够得到如下值。

if let messageString = userInfo[AnyHashable("message")] as? String {

                    if let dictionaryMessage = UtilityMethods.shared.convertToDictionary(text: messageString) {

                        if let messageBody = dictionaryMessage["body"] as? String {

                            if let sender = dictionaryMessage["sender"] as? [String:Any] {
                                if let senderName = sender["name"] as? String {


                                }
                            }
                        }
                    }

                }

将 JSON 字符串转换为字典的函数

func convertToDictionary(text: String) -> [String: Any]? {
        if let data = text.data(using: .utf8) {
            do {
                return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
            } catch {
                print(error.localizedDescription)
            }
        }
        return nil
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 2011-11-12
    • 2011-02-07
    • 2018-08-27
    相关资源
    最近更新 更多