ios - 如何使用 Firestore 数据库在 swift 中为 tableview 中的项目列表设置 postkey?
问题描述
如何使用 Firestore 数据库在 swift 中为 tableview 中的项目列表设置 postkey?
从昨天开始我尝试了很多东西,但都没有用。我需要使用 postkey 在帖子上发布评论。
在我正在关注的代码下方
发布模型 Swift 文件
import Foundation
import Firebase
import FirebaseFirestore
protocol DocumentSerializable {
init?(dictionary:[String:Any])
}
struct Post {
// var name:String
// var content:String
//var timeStamp:Date
var username: String!
var postTitle: String!
// var postKey: String!
var postcategory: String!
var postContent: String!
//private var _postRef: DocumentReference!
var dictionary:[String:Any] {
return [
"username": username,
//"profile_pic":profile_pic,
"postTitle":postTitle,
"postcategory":postcategory,
"postContent":postContent
// "postKey":postKey
]
}
}
extension Post : DocumentSerializable {
init?(dictionary: [String : Any]) {
guard let username = dictionary["username"] as? String,
// let profile_pic = dictionary["profile_pic"] as? String,
let postTitle = dictionary["postTitle"] as? String,
let postcategory = dictionary["postcategory"] as? String,
let postContent = dictionary["postContent"] as? String else { return nil }
// let postKey = dictionary["postKey"] as? String
self.init(username: username, postTitle: postTitle, postcategory: postcategory, postContent: postContent )
}
}
用于在 tableview 中登记帖子的 ViewController 类
import Foundation
import UIKit
import Firebase
class HomeViewController:UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView:UITableView!
var posts = [Post]()
var db: Firestore!
private var documents: [DocumentSnapshot] = []
//public var posts: [Post] = []
private var listener : ListenerRegistration!
override func viewDidLoad() {
super.viewDidLoad()
db = Firestore.firestore()
self.navigationController?.navigationBar.isTranslucent = false
tableView = UITableView(frame: view.bounds, style: .plain)
let cellNib = UINib(nibName: "PostTableViewCell", bundle: nil)
tableView.register(cellNib, forCellReuseIdentifier: "postCell")
tableView.backgroundColor = UIColor(white: 0.90,alpha:1.0)
view.addSubview(tableView)
var layoutGuide:UILayoutGuide!
if #available(iOS 11.0, *) {
layoutGuide = view.safeAreaLayoutGuide
} else {
// Fallback on earlier versions
layoutGuide = view.layoutMarginsGuide
}
tableView.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
tableView.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true
tableView.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true
tableView.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true
tableView.delegate = self
tableView.dataSource = self
tableView.reloadData()
retrieveAllPosts()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func handleLogout(_ sender:Any) {
try! Auth.auth().signOut()
self.dismiss(animated: false, completion: nil)
}
func retrieveAllPosts(){
let postsRef = Firestore.firestore().collection("posts").limit(to: 50)
postsRef.getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
print("\(document.documentID) => \(document.data())")
self.posts = querySnapshot!.documents.flatMap({Post(dictionary: $0.data())})
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
cell.set(post: posts[indexPath.row])
return cell
}
}
解决方案
这不是一个简单的帖子键,您需要在该列表中创建名为“comments”的帖子的子文档,您需要添加commentContent、byUser、toUser、onPost等。仅添加 postKey 不会解决您的问题
举个简单的例子
let postId = "45f4854fjrh4" // documentId of post
let commentData = [commentContent:"this is comment", "commenterId":"242343f3ffd3", "postId": postId, "commentName":"\(youProfileName)", "onPost":"45454252342","postOwnerId":"34343434543"
注意:您可以根据需要设置以下或以上数据
Firestore.firestore().collection("posts/\(postId)/Comments").addDocument(commentData)
对于击球手的理解,您可能会看到下面的房间示例
推荐阅读
- c++ - 通过引用传递对 lambda 的引用
- linux - Kubernetes 工作空间中的持久卷和声明
- css - 将元素放置在“闪亮”应用程序中,以便它们调整移动和桌面显示器的大小
- ios - 将 Powerapps 投射到 Chromecast
- solr - 分片处于“恢复”状态,副本都处于“活动状态”
- postgresql - 在 Postgresql 中删除字符
- apache-spark - 如何将带有时区的奇怪日期时间字符串转换为时间戳(PySpark)
- android - 如何在Android上的recyclerView中使用多个计时器
- android - 调试输出上的 Android net::ERR_CACHE_MISS
- python - 暂停 Jupyter Notebook 小部件,等待用户输入