如何将'FIRDataSnapshot'转换为NSString& NSDict

时间:2017-11-06 21:12:06

标签: ios swift firebase

我收到的错误是无法将'FIRDataSnapshot'类型的值转换为'NSString'。检索名称或检索数量/制造商都不起作用。两者都给出了相同的铸造误差。

ref = Database.database().reference()

    // Retrieve Names

    ref.child("rawMaterials").observeSingleEvent(of: .value, with: { (snapshot) in
        for child in snapshot.children {
            self.rawMaterialNames.append(child as! String)
        }
    })
    //Retrieve Quantities and Manfacturers

    for name in rawMaterialNames {
        ref.child("rawMaterials/\(name)").observe(.value, with: { (snapshot) in
            if let data = snapshot.value as? [String: Any] {
                for i in data {
                    let quantity = data["quantity"] as! String
                    let manafacturer = data["manafacturer"] as! String
                    self.rawMaterialManafacturers.append(manafacturer)
                    self.rawMaterialQuantities.append(quantity)
                  //self.rawMaterialQuantities.append(data!["quantity"] as! String)
                  //self.rawMaterialManafacturers.append(data!["manafacturer"] as! String)
                }
            }
        })

编辑:既然,没有人能够提供帮助,也许我提供的不够。我的firebase实时数据库树看起来像这样

应用名称

-contracts

--- ContractTest

-rawMaterials

---可选( “画图”)

-------- manafacturer:“可选(\”Paint Company A \“)”

--------数量:“可选(\”120 \“)”

---可选( “铅”)

1 个答案:

答案 0 :(得分:0)

您错过了一个能够转换为String的步骤:

ref.child("rawMaterials").observeSingleEvent(of: .value, with: { (snapshot) in
    for child in snapshot.children {
        let nameSnapshotValue = child.value as! FIRDataSnapshot
        let name = nameSnapshotValue["name"] as! String //or whatever the dictionary key is...
        self.rawMaterialNames.append(name)
    }
})