0
我一直在iOS中第一次使用Firebase。我已成功写入数据的火力点,并像这样组织的:Firebase没有检索数据(iOS)
{
"users" : {
"6ytX7ZLa28MYXX8zm3gawJiOYuY2" : {
"-Kmj196aXH9uRXd-bCgB" : {
"category" : "Work",
"date" : "Jun 16, 1:54 AM ",
"place" : "Tampa, Forida",
"title" : "make an app"
},
"-Kmj1HcNcDb9gD2TTlQB" : {
"category" : "Design",
"date" : "Jun 18, 12:58 AM ",
"place" : "Sarasota",
"title" : "Design an app"
}
}
}
}
目前,我有下面的代码来尝试恢复数据,但它渲染不成功。任何你可以提供的帮助将非常感谢!
TableViewController:
import UIKit
import Firebase
import FirebaseDatabase
class TasksHome: UITableViewController {
private var databaseHandle: FIRDatabaseHandle!
var ref: FIRDatabaseReference!
var user: FIRUser!
var username: String!
var items = [Item]()
override func viewDidLoad() {
super.viewDidLoad()
user = FIRAuth.auth()?.currentUser
username = FIRAuth.auth()?.currentUser?.uid
ref = FIRDatabase.database().reference()
startObservingDatabase()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TasksHomeCell
let item = items[indexPath.row]
cell.titleLabel.text = item.title
cell.categoryLabel.text = item.category
cell.placeLabel.text = item.place
cell.dateLabel.text = item.date
return cell
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let item = items[indexPath.row]
item.ref?.removeValue()
}
}
func startObservingDatabase() {
databaseHandle = ref?.child("users").child(self.username).observe(.value, with: { (snapshot) in
let userDict = snapshot.value as! [String: Any]
let category = userDict["category"] as! String
let date = userDict["date"] as! String
let title = userDict["title"] as! String
let place = userDict["place"] as! String
print("category: \(category) date: \(date) title: \(title) place: \(place)")
})
}
deinit {
ref.child("users/\(self.user.uid)/items").removeObserver(withHandle: databaseHandle)
}
}
项目文件
import Foundation
import FirebaseDatabase
class Item {
var ref: FIRDatabaseReference?
var title: String?
var category: String?
var date: String?
var place: String?
init (snapshot: FIRDataSnapshot) {
ref = snapshot.ref
let data = snapshot.value as! Dictionary<String, String>
title = data["title"]! as String
category = data["category"]! as String
date = data["date"]! as String
place = data["place"]! as String
}
}
谢谢大家的帮助!
1:引发的任何错误?如果是的话,你可以将它们添加到你的问题。 2:是否调用'startObservingDatabase()'中的print语句? – eshirima
你好,Eshirima!运行时不会引发错误,并且不会调用print语句。在其他地方调用时,所有成分都返回零。 –
你的意思是什么?当其他地方调用时,它对所有的成分都返回零?你也需要遍历'snapshot'来获取它的内容,因为它由其他字典组成。它是一本字典词典。注释掉完成处理程序中的所有内容,并简单地写入'print(snapshot)'来看看它的样子 – eshirima