我有一个tableView,它有大约5个单元格,每个单元格都有不同的主题。单击单元格后,我想转到一个视图控制器,该控制器填充了Firebase数据,该数据仅包含单击特定主题的帖子。
override func viewDidLoad() {
super.viewDidLoad()
FIRDatabase.database().reference().child("books").observeSingleEvent(of: .value, with: { (snapshot:FIRDataSnapshot) in
if let postsDictionary = snapshot .value as? [String: AnyObject] {
self.Category = postsDictionary["Category"] as? String ?? ""
}})
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segue" {
let showBooks = segue.destination as! SearchTableViewController
showBooks.categorySegue = self.Category
}
}
在我的Firebase数据库中,我有一堆由不同用户制作的帖子,在每个帖子中,他们都设置了帖子所属的类别。例如,如果我点击具有主题的tableView单元格:经济学,我想转到仅具有经济学类别的视图控制器。
这是我检索归因于某些主题的帖子的方式:
databaseRef.child("books").queryOrdered(byChild: "category").queryEqual(toValue: categorySegue).observeSingleEvent(of: .value, with: { (snapshot) in
let key = snapshot.key
let snapshot = snapshot.value as? NSDictionary
snapshot?.setValue(key, forKey: "uid")
if(key == self.loggedUser?.uid)
{
print("same as logged in user")
}
else
{
self.usersArray.append(snapshot)
self.followUsersTableView.insertRows(at: [IndexPath(row:self.usersArray.count-1,section:0)], with: UITableViewRowAnimation.automatic)
}
}) { (error) in
print(error.localizedDescription)
}
tableView.tableFooterView = UIView()
答案 0 :(得分:1)
如果类别位于uniqueID下的posts节点的正下方,请尝试此
示例:
posts
-> post_id1
->category : "books"
-> other keys
-> post_id2
->category : "music"
-> other keys
按类别提取帖子的查询将是这样的,
let strCategory = "music"
baseRef.child("posts").queryOrdered(byChild: "category").queryEqualToValue(strCategory).observeSingleEvent(of: .value, with: { (snapshot) in
print(snapshot)
})
要在选择时获取单元格索引,
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let indexPath = tableView.indexPathForSelectedRow{
let selectedRow = indexPath.row
let categorySelected = Subjects[selectedRow]
}
}