从firebase中选择选定的数据(快速)

时间:2018-10-18 19:52:25

标签: swift firebase firebase-realtime-database

enter image description here

我想选择照片中出现的数据,例如“ 2”和“ 123”。这个“ 2”和“ 123”作为我要通过firebase数据库选择的芯片ID。因此,我只想在firebase中获取某些数据,而不是获取chipItem中的所有数据。

    ref.observe(.value, with: { (snapshot: DataSnapshot) in

        self.items.removeAll()

        for chipItem: DataSnapshot in snapshot.children.allObjects as! [DataSnapshot]{



            let chipId: String = chipItem.key


            let titles: DataSnapshot = chipItem.childSnapshot(forPath: "titles")




            for device in titles.children.allObjects as! [DataSnapshot]{

                print("Got device: ", device)

                let value: NSDictionary = device.value as! NSDictionary

                let deviceTitle: String = value["title"] as! String
                let deviceId: String = value["id"] as! String

                let deviceState: Bool = chipItem.childSnapshot(forPath: "states/\(deviceId)").value as! Bool

                let newDevice = Device()

                newDevice.title = deviceTitle
                newDevice.chipId = chipId
                newDevice.state = deviceState
                newDevice.id = deviceId

                self.items.append(newDevice)
            }

        }


        self.tableView.reloadData()




    }) { (err:Error) in

        print("got an error: ", err)
    }

2 个答案:

答案 0 :(得分:0)

使用queryEqualToValue()

ref.queryEqual(toValue: "123").observeSingleEvent(of: .value) { (snapshot) in 
    ...
}

根据需要使用observeSingleEvent() or observe()

答案 1 :(得分:0)

`chipItem:snapshot.children.allObjects中的DataSnapshot为! [DataSnapshot] {

let chipId:字符串= chipItem.key`

在这里,我需要进行一些与您的工作方式不同的更改。我需要调用“ snapshot.children.allObjects”而不是allObjects。