【问题标题】:Can't view Firebase data in tableview Swift 4无法在 tableview Swift 4 中查看 Firebase 数据
【发布时间】:2019-05-09 12:39:16
【问题描述】:

我遇到了一个问题,我无法在表格视图中查看写入 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()
        }
    })
   }

【问题讨论】:

    标签: swift firebase firebase-realtime-database tableview


    【解决方案1】:

    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
    }
    

    【讨论】:

    • 我不明白你所说的“以同样的方式绑定”是什么意思?我尝试了一些方法,但仍然遇到问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多