firebase子值作为数组中的字符串来填充选择器swift 3

时间:2017-02-10 07:25:31

标签: arrays swift string firebase firebase-realtime-database

如何使用已放入数组的Firebase值来弹出选择器。这是我用来向数组添加值并打印它们的代码:

let dbRef1 = FIRDatabase.database().reference().child("Live Scoring Male")

    dbRef1.observe(.childAdded, with: { snapshot in

        let data = snapshot.value as? [String:Any] ?? [:]
        let name = data["name"] as? String ?? ""
        self.compArray.append(name)
        print("\(name)")

    })

但是,当我调用时,数组值不会被加载到选择器中:

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

    if (pickerView.tag == 1) {
        return compArray[row]
    }
}

如果我在数组中对字符串进行硬编码,但是如果我尝试从Firebase加载值,则此代码无效。

2 个答案:

答案 0 :(得分:1)

您需要重新加载pickerView组件以使用新的dataSource数组更改它。

let dbRef1 = FIRDatabase.database().reference().child("Live Scoring Male")

dbRef1.observe(.childAdded, with: { snapshot in

    if let dic = snapshot.value as? [String:Any], let name = dic["name"] as? String { 
        self.compArray.append(name) 
        print("\(name)")

        //Reload the pickerView components
        self.pickerView.reloadAllComponents()

        //Or you can reload the pickerView's specific component
        self.pickerView.reloadComponent(0)
    }
}) 

答案 1 :(得分:0)

首先,您必须将快照转换为字典,然后从字典中访问该名称:

let data = snapshot.value as? [String:Any] ?? [:]
let name = data["name"] as? String ?? ""
self.compArray.append(name)