我真的是使用swift进行IOS开发的新手,我想知道为什么当我尝试用从Firestore集合中检索到的数据填充TableView时收到一个空的TableView。
完全没有错误。我尝试
时会收到数据print()
是因为SnapshotListener吗?
import UIKit
import FirebaseStorage
import FirebaseFirestore
struct Posts {
var caption:String
}
class LentaViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var posts = [Posts]()
override func viewDidLoad() {
super.viewDidLoad()
loadPosts()
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
func loadPosts() {
let dbUsers = Firestore.firestore().collection("posts")
dbUsers.addSnapshotListener { (querySnapshot, error) in
if let error = error {
print("\(error.localizedDescription)")
} else {
for document in (querySnapshot?.documents)! {
if let Caption = document.data()["caption"] as? String {
print(Caption)
var post = Posts(caption: "")
post.caption = Caption
self.posts.append(post)
}
}
DispatchQueue.main.async
{
self.tableView.reloadData()
}
print(self.posts)
}
}
}
}
extension LentaViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let post = posts[indexPath.row]
cell.textLabel?.text = post.caption
return cell
}
}
答案 0 :(得分:0)
您没有将tableView.dataSource
属性分配给LentaViewController
实例。在viewDidLoad()
中分配它。另外,无需在ViewDidLoad()
中重新加载tableView。
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
loadPosts()
}