gpt4 book ai didi

ios - 根据用户名显示 Firebase 数据

转载 作者:行者123 更新时间:2023-11-30 12:40:41 27 4
gpt4 key购买 nike

我目前有一个 UITableView,在单元格中显示 Firebase 数据库中的帖子。还有另一个 UITableView,我想仅显示登录用户的帖子。

这是我当前在 UserPostViewController 中的内容:

func loadData() {
let uid = FIRAuth.auth()?.currentUser?.uid
FIRDatabase.database().reference().child("posts").child(uid!).observeSingleEvent(of: .value, with: {
(snapshot) in
if let postsDictionary = snapshot.value as? [String: AnyObject] {
for post in postsDictionary {
self.userPosts.add(post.value)
}
self.userPostsTableView.reloadData()
}
})
}

// MARK: - Table view data source

func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// pass any object as parameter, i.e. the tapped row
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.userPosts.count
}

// Displays posts in postsTableView
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) as! PostTableViewCell
// Configure the cell...
let post = self.userPosts[indexPath.row] as! [String: AnyObject]
cell.titleLabel.text = post["title"] as? String
cell.priceLabel.text = post["price"] as? String
if let imageName = post["image"] as? String {
let imageRef = FIRStorage.storage().reference().child("images/\(imageName)")
imageRef.data(withMaxSize: 25 * 1024 * 1024, completion: { (data, error) -> Void in if error == nil {
let image = UIImage(data: data!)
cell.titleLabel.alpha = 0
cell.contentTextView.alpha = 0
cell.postImageView.alpha = 0
UIView.animate(withDuration: 0.4, animations: {
cell.titleLabel.alpha = 1
cell.contentTextView.alpha = 1
cell.postImageView.alpha = 1
})
} else {
print("Error occured during image download: \(error?.localizedDescription)")
}
})
}
return cell
}

这也是我在 Firebase 中的意思的图片:

Here

最佳答案

Firebase 是一个 NoSQL 数据库。尝试在其上转换 SQL 实践将会给您带来痛苦。

不要存储一长串帖子,然后使用查询进行过滤,而是将每个用户的帖子存储在特定于用户的节点下。即

users
$uid
username: "gabe"
posts
$uid
-K12348: {
description: "...."
image: "...."
}

现在,您可以通过直接访问读取来访问特定用户的帖子,而不是在不断增长的列表上查询:

FIRDatabase.database().reference().child("posts").child(uid!).observeSingleEvent(of: .value, with: {
(snapshot) in
if let postsDictionary = snapshot.value as? [String: AnyObject] {
for post in postsDictionary {
self.userPosts.add(post.value)
}
self.userPostsTableView.reloadData()
}

下次请将您的 JSON 作为文本发布,以便我可以将其复制/粘贴到我的答案中。

我建议阅读NoSQL data modeling并查看Firebase for SQL developers .

关于ios - 根据用户名显示 Firebase 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42263204/

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