Search code examples
swiftfirebasefirebase-realtime-databasesigabrt

Reading child value from firebase database in swift


I am trying to read a child value so I can add 1 to it then update the value, but my code to read the value is giving me a SIGABRT error and crashing, what is wrong with it? REF_FEEDMESSAGES is a reference to the database that holds all the messages

var stringLikes = REF_FEEDMESSAGES.child(key).value(forKey: "likes") as! String ?? "0"

Solution

  • You need ( observe / observeSingleEvent is up to you according to the logic of your app )

    REF_FEEDMESSAGES.child("\(key)/likes").observeSingleEvent(of: .value, with: { (snapshot) in
      // Get user value
    
      }) { (error) in
        print(error.localizedDescription)
    }
    

    Using this .value(forKey: "likes") as! String for sure will crash the app , as it's not a local dictionary to query it's data synchronously