Firebase Query snapshot nil?

后端 未结 3 1554
孤独总比滥情好
孤独总比滥情好 2020-12-20 12:10

I\'m creating a simple chat app to learn Swift and Firebase. I have a query that checks for a chat room\'s messages to load into a tableView. The query returns a snapshot bu

3条回答
  •  孤城傲影
    2020-12-20 12:53

    Your dictionary look like :

    ▿ 1 element
      ▿ 0 : 2 elements
        - key : "-KotqLUUucaRagTRt967"
        ▿ value : 3 elements
          ▿ 0 : 2 elements
            - key : sender
            - value : eGTYRSo81JefgasYLRHUFHUTnEC3
          ▿ 1 : 2 elements
            - key : text
            - value : test
          ▿ 2 : 2 elements
            - key : timestamp
            - value : 1499914135546
    

    But in fact it should look like (If you want to access to dictionary["sender"]) :

    ▿ 2 elements
      ▿ 0 : 2 elements
        - key : sender
        - value : eGTYRSo81JefgasYLRHUFHUTnEC3
      ▿ 1 : 2 elements
        - key : text
        - value : test
      ▿ 2 : 2 elements
        - key : timestamp
        - value : 1499914135546
    

    First solution :

    You need to add .child("-KotqLUUucaRagTRt967") in your query.

    OR

    Second solution :

    You need to do something like that :

    query.observe(.childAdded, with: { snapshot in
        for child in snapshot.children {
            guard let value = child.value as? NSDictionary else {
                return
            }
    
            guard let sender = value["sender"] as? String else {
                return
            }
    
            // You can user the sender
        }
    })
    

    UPDATE :

    query.observe(.childAdded, with: { snapshot in
        for child in snapshot.children.allObjects as! [FIRDataSnapshot] {
            if let value = child.value as? [String:Any], let sender = value["sender"] as? String {  
                // You can user the sender
            }
        }
    })
    

    NOTE

    I replaced observeSingleEvent with observe, as Frank van Puffelen said, it's an uncommon combination for .childAdded.

提交回复
热议问题