我是编程新手,目前正在尝试制作类似应用程序的新闻源。我的目标是通过我的应用程序和表格 View 中的新帖子来注意 firebase 数据库中的更改。目前我可以在我的 tableView 中显示一篇文章。它只会在您重新打开 ViewController 时发生变化。 我的问题之一是我不知道如何使用任何其他命令然后使用 obserSingleEvent,我很确定这是我的主要错误之一。 所以我的问题是: 1. 如何让 tableView 在发生变化时立即重新加载? 2. 如何显示多个帖子? (3. 如何优先显示最新的帖子?)
class ViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var newsfeedTableView: UITableView!
var ref: DatabaseReference!
var posts = [String]()
override func viewDidLoad() {
super.viewDidLoad()
addSlideMenuButton()
ref = Database.database().reference()
ref.child("posts").queryOrderedByKey().observeSingleEvent(of: .childAdded, with: { snapshot in
let newPost = snapshot.value as? String
self.posts.append(newPost!)
print("newPost: \(newPost)")
print("posts: \(self.posts)")
self.newsfeedTableView.reloadData()
print("reloadData")
})
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (posts.count)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "cell")
cell.textLabel?.text = posts[indexPath.row]
print("posts in cell: \(posts)")
return cell
}
}
最佳答案
您正在使用 singleEvent
进行观察,这对于预期用途是错误的。
ref.child("posts").observe( .childAdded, with: { snapshot in
let newPost = snapshot.value as? NSDictionary
let post_title:String = newPost!["post_title"] as? String ?? "error"
self.posts.append(post_title)
print("newPost: \(newPost)")
print("posts: \(self.posts)")
self.newsfeedTableView.reloadData()
print("reloadData")
})
此外,该排序系统不适用于新闻应用。你不能使用人类提供的 1,2,3。从现在开始你能把它更新成这样吗:
(1 - 2) 随机生成的唯一帖子 ID
附言。 Firebase 不可能用 post、post1、post2 对你的帖子列表进行排序。所以在这种情况下 queryOrderedByKey()
是没有用的。
将帖子 1、2、3 用于订购系统
关于ios - 在 UITableView 数组中保存 Firebase 结构 [Swift 4],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53631680/