我目前在读取 Firebase 数据库并将其显示到表列表中时遇到麻烦。下面是我在当前 View Controller 中使用的代码。
import UIKit
import Firebase
import FirebaseDatabase
class Buy_1: UIViewController, UITableViewDataSource,
UITableViewDelegate {
var ref: DatabaseReference!
var databaseHandle: DatabaseHandle!
var postItem: [String] = []
@IBOutlet weak var TableView: UITableView!
@IBAction func goBackToOneButtonTapped(_ sender: Any) {
performSegue(withIdentifier: "unwindSegueToVC1", sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
if FirebaseApp.app() == nil {
FirebaseApp.configure()
}
//Set Self as tableview's data source and delegate
self.TableView.delegate = self
self.TableView.dataSource = self
//Set the firebase reference
ref = Database.database().reference()
//Retrieve and listen for changes
databaseHandle = ref?.child ("items").observe(.childAdded, with: { (snapshot) in
//Convert value of data into string
if let item = snapshot.value as? String
{
self.postItem.append(item)
self.TableView.reloadData()
self.ref?.keepSynced(true)
}
/*if let actualItem = item {
//Appends data to our Item Array
self.postItem.append(actualItem)
//Reload TableView
self.TableView.reloadData()
}*/
})
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
//MARK: - UITableView Delegate Methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postItem.count
}
func tableView(_ TableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = TableView.dequeueReusableCell(withIdentifier: "BasicCell", for: indexPath)
cell.textLabel?.text = postItem[indexPath.row]
return cell
}
}
我没有收到代码中的任何错误,所以我不确定出了什么问题。 &我已经将数据库规则设置为true。
谢谢。
最佳答案
您正在观察.childAdded
,只有当将子项添加到您观察到的数据树时,它才会触发您的 block 。
将其更改为 .value
。
关于ios - 为什么我的 iOS 应用程序无法从 Firebase 数据库读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53463335/