我无法将我的firebase数据显示在tableviewcell中。我已阅读了数十个问题,但似乎没有相同的设置和问题。
我在TableViewController的viewDidLoad中设置了观察者:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Setup observers that perform a closure each time a book is added,
// removed, or changed.
func setupDBListeners() {
// returns each book in order by title.
let ref = FIRDatabase.database().reference()
ref.child(K.bookKey)
.queryOrdered(byChild: K.titleKey)
.observe(.childAdded, with: { (snapshot) in
let book = self.convertSnapshotToBookObj(snapshot)
self.books.append(book)
self.tableView.reloadData()
})
// Listen for changes in book data.
ref.child(K.bookKey)
.observe(.childChanged, with: { (snapshot) in
let book = self.convertSnapshotToBookObj(snapshot)
for i in 0...self.books.count {
if self.books[i].id == book.id {
self.books[i] = book
self.tableView.reloadData()
return
} }
})
// Listen for books removed.
ref.child(K.bookKey)
.observe(.childRemoved, with: { (snapshot) in
let book = self.convertSnapshotToBookObj(snapshot)
for i in 0...self.books.count {
if self.books[i].id == book.id {
self.books.remove(at: i)
self.tableView.reloadData()
return
} }
}) }
}
然后在我之外我有一个函数将它转换为数组的对象:
func convertSnapshotToBookObj(_ snap: FIRDataSnapshot) -> Book {
let bookValues = snap.value as! [String : AnyObject]
let id = snap.key
let author = bookValues[K.authorKey] == nil ? "" : bookValues[K.authorKey]! as! String
let title = bookValues[K.titleKey] == nil ? "" : bookValues[K.titleKey]!
as! String
let year = bookValues[K.yearKey] == nil ? "" : bookValues[K.yearKey]! as!
String
// Return a book object with the properties set.
let book = Book()
book.id = id
book.author = author
book.title = title
book.year = year
self.tableView.reloadData()
return book
}