gpt4 book ai didi

ios - 如何使用 Firestore 数据库快速设置 TableView 中项目列表的后缀?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:58:07 24 4
gpt4 key购买 nike

如何使用 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 )
}
}

ViewController 类用于在 tableview 中获取帖子

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
}
}

最佳答案

它不会是一个简单的帖子 key ,您需要在该列表中创建名为“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)

为了更好地理解,您可以查看下面的房间示例

How to add subcollection to a document in Firebase Cloud Firestore

关于ios - 如何使用 Firestore 数据库快速设置 TableView 中项目列表的后缀?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57703797/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com