Read Data Firebase assign value

…衆ロ難τιáo~ 提交于 2020-07-28 04:52:08

问题


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 not being assigned. I want to assign deviceroom1, deviceRoom2, deviceRoom3, deviceRoom4.

    var deviceRoom1: String = ""
    var deviceRoom2: String = ""
    var deviceRoom3: String = ""
    var deviceRoom4: String = ""
    var deviceRoom5: String = ""

 func fetchDevies(){

        let ref = Database.database().reference().child(self.chip1InfoString!).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

            }
            if let deviceRooms2 = value?["Rooms2"] as? String {
                self.deviceRoom2 = deviceRooms2

            }
            if let deviceRooms3 = value?["Rooms3"] as? String {
                self.deviceRoom3 = deviceRooms3

            }
            if let deviceRooms4 = value?["Rooms4"] as? String {
                self.deviceRoom4 = deviceRooms4

            }
            if let deviceRooms5 = value?["Rooms5"] as? String {
                self.deviceRoom5 = deviceRooms5

            }
        }) { (error) in
            print(error.localizedDescription)
        }

                let items = [deviceRoom1, deviceRoom2, deviceRoom3, deviceRoom4, deviceRoom5]

回答1:


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



来源:https://stackoverflow.com/questions/56025373/read-data-firebase-assign-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!