Read Data Firebase assign value

前端 未结 1 1987
情书的邮戳
情书的邮戳 2020-12-22 12:05

I want to assign the data I have read in the Firebase database to the values I have given in the code. The data is being read in the code I have given, but the values are no

相关标签:
1条回答
  • 2020-12-22 12:14

    This issue is that Firebase is asynchronous so you need to give Firebase time to fetch and return the requested data. i.e. the data is only valid within the closure.

    Your code is assigning values with let items = ... outside the closure and that code will execute way before the data is returned. Move the assignment inside like closure like this (code is shortened for brevity)

    func fetchDevies() {
        let ref = Database.database().reference().child("some_node").child("Rooms")
        ref.observeSingleEvent(of: .value, with: { snapshot in
            let value = snapshot.value as? NSDictionary
    
            if let deviceRooms1 = value?["Rooms1"] as? String  {
                self.deviceRoom1 = deviceRooms1
            }
            .
            .
            .
            let items = [self.deviceRoom1, self.deviceRoom2, self.deviceRoom3, self.deviceRoom4, self.deviceRoom5]
            print(items)
        })
    
        //code here will run before Firebase has returned data and populated the vars
    

    Also, be careful with var names. If you are accessing a class var, always refer to it with self. like self.deviceRoom1

    0 讨论(0)
提交回复
热议问题