无法在Tableview Swift 4中查看Firebase数据

时间:2018-12-07 18:01:49

标签: swift firebase firebase-realtime-database tableview

我遇到一个问题,即无法在表视图中查看写入Firebase数据库的任何内容。我以前有一些工作代码来查看数据库条目,但必须修改将数据写入数据库的方式,这样我才能保存childByAutoID()生成的唯一ID,因此以后可以删除条目。这是我的代码:

在这里我如何写Firebase:

ref = Database.database().reference() //  sets the variable "ref" to connect to our Firebase database
 let key = ref?.child("task").childByAutoId().key
            let post = ["uid": key,       // Gets auto generated ID for database entry
                        "title": input.text,                    // Saves the title field to Firebase
                        "description": inputField.text]         // Saves the description field to Firebase
            ref?.child("task").child(key!).setValue(post)      // Saves the task for Firebase, ties each post with a unique ID

            var arr : [(String, String)] = [];
            for (key, value) in post {
                arr.append((key, value!));

这里是我的TableViewController:

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    return (arr.count)
}


public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    let cell = UITableViewCell(style: 
UITableViewCell.CellStyle.default, reuseIdentifier: "cell")

    let (key, value) = arr[indexPath.row]; //read element for the desired cell
    cell.textLabel?.text = key
    cell.detailTextLabel?.text = value
    return (cell)
}        
override func viewDidAppear(_ animated: Bool) {//change "viewDidLoad()" back to "viewDidAppear()"
    ref = Database.database().reference()                  // sets the variable "ref" to connect to our Firebase database

    list.removeAll()    // Deletes all older data, so only data thats on the Firebase Database will be added to the "list" array
    desc.removeAll()    // Deletes all older data, so only data thats on the Firebase Database will be added to the "desc" array

    handle = ref?.child("task").observe(.childAdded, with: { (snapshot) in

if let item = snapshot.value as? String
        {
            arr.append(item)
            list.append(item)
            //desc.removeAll()
            self.myTableView.reloadData()
        }
    })
   }

1 个答案:

答案 0 :(得分:0)

FirebaseNSArrayNSDictionaryNSString的形式返回项目。 (Refer here) 由于您的post对象为NSDictionary,因此将快照值解析为字典数组。尝试以下操作:

if let itemArray = snapshot.value as? [[String : Any]] {

  // Looping logic on 'itemArray' to get your sent dictionaries on the firebase 
  // After looping logic add Ui logic out of loop
}