我正在尝试使用
从Firebase下载数据 firebaseDB.observe(DataEventType.value, with: { (snapshot) in })
效果很好。我能够收到以下数据:
let fetchedObject = items.value as? [String: AnyObject]
let dbUrl = fetchedObject?["url"]
let dbTime = fetchedObject?["time"]
let dbStatus = fetchedObject?["status"]
使用print("\(dbUrl!), \(dbTime!), \(dbStatus!)")
,我在控制台中看到以下输出:
https://google.de,2019-04-26 07:44:54 +0000,新
但是,因为我想在Tableview中显示数据,所以我为数据模型创建了一个名为ItemModel
的快速文件,其内容如下:
class ItemModel {
var url: String?
var time: String?
var status: String?
init(url: String?, time: String?, status: String?){
self.url = url
self.time = time
self.status = status
}
}
当尝试使用填充网址,时间和状态时
let item = ItemModel(url: dbUrl as! String?, time: dbTime as! String?, status: dbStatus as! String?)
用self.itemList.append(item)
附加它,并用self.tableViewOutlet.reloadData()
重新加载表,应用程序崩溃。
如果我将self.itemList.append(item)
注释掉,它不会崩溃。
我在做什么错?我显然错过了一些可行的方法,但是我只是想不出什么。我真的很想知道为什么附加数据不起作用...非常感谢您的帮助!
编辑:
完整的提取方法:
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var itemList = [ItemModel]()
override func viewDidLoad() {
super.viewDidLoad()
[...]
// Authenticate user
Auth.auth().signInAnonymously() {(authResult, error) in
if error == nil {
self.user = authResult!.user // Authenticate User
self.uid = self.user.uid // Users unique and anonymous identifier by Firebase
print(">> LOG: Auth success!")
// Download data from Firebase
var itemsDB: DatabaseReference!
itemsDB = Database.database().reference().child("somechild").child("someotherchild")
itemsDB.observe(DataEventType.value, with: { (snapshot) in
// Check if there is any relevant data
if snapshot.childrenCount > 0 {
// Initially clear the list
self.itemList.removeAll()
// Interate through all the values
for items in snapshot.children.allObjects as! [DataSnapshot] {
// Get the values from Firebase
let fetchedObject = items.value as? [String: AnyObject]
let dbUrl = fetchedObject?["url"]
let dbTime = fetchedObject?["time"]
let dbStatus = fetchedObject?["status"]
let item = ItemModel(url: dbUrl as? String, time: dbTime as? String, status: dbStatus as? String)
print("\(item.url!), \(item.time!), \(item.status!)")
self.itemList.append(item)
}
// Reload the Tableview
self.tableViewOutlet.reloadData()
}
})
} else {
print(">> LOG: Error when trying to authenticate: \(error!)")
}
}
}
}