我正在构建一个应用程序,允许用户扫描条形码并存储书籍信息并将其检索到TableView。这些书籍存储在当前用户ID下 - >书籍 - >这本书的名字 - >标题,作者..等等。请参阅下面的JSON结构: -
因此,有不同名称的书籍,每次扫描新书时,都会在“书籍”下添加。
如何以不同的名义获取所有图书的数据?
这里是代码,我试图在TableViewController中检索数据:
var posts = [BooksFromFirebase]()
override func viewDidLoad() {
super.viewDidLoad()
//get reference to data location
let databaseRef = Database.database().reference()
//get current user id
let user = Auth.auth().currentUser
databaseRef.child("users").child((user?.uid)!).child("books").observe(.value, with: { (snapshot) in
if let value = snapshot.value as? [String: AnyObject]{
let assetTitle = value["title"] as? String ?? ""
print("Title ",assetTitle)
let title = assetTitle
let type = "Book"
self.posts.insert(BooksFromFirebase(title: title, type: type), at: 0)
self.tableView.reloadData()
}
})
}
答案 0 :(得分:0)
尝试使用: -
Database.database().reference().child("users/(user!.uid)/books").observeSingleEvent(of: .value, with: {(Snapshot) in
if let eachDict = Snapshot.value as? NSDictionary{
for each in eachDict{
print(each.key ?? "No Data")
print(each.value ?? "No Data")
print((each.value as! NSDictionary)["title"] ?? "No data")
}
}
}, withCancel: {(Err) in
// Handle error encountered while communicating via firebase
})