gpt4 book ai didi

swift - 如何过滤 Firebase 数据库中的数据?

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

如何更改我的网络文件和 homeviewController 中的 fetchAllPosts 函数,以便我只从数据库中获取与我的用户 UID 匹配的帖子我关注的是 post.UID,所以我的提要中充满了我关注的用户的帖子?

这是显示我如何在数据库中创建新关注者的引用:

let followingRef = "following/" + (self.loggedInUserData?["uid"] as! String) + "/" + (self.otherUser?["uid"] as! String)

这是 Firebase 数据库中的帖子结构

posts
-Ke4gQKIbow10WdLYMTL (generated key)
postDate:
postId:
postPicUrl:
postText:
postTit:
type:
uid: looking to match this

这是网络文件中当前的 fetchAllPosts 函数

func fetchAllPosts(completion: @escaping ([Post])->()) {

let postRef = self.dataBaseRef.child("posts")
postRef.observe(.value, with: { (posts) in

var resultsArray = [Post]()
for post in posts.children {

let post = Post(snapshot: post as! FIRDataSnapshot)
resultsArray.append(post)

}

completion(resultsArray)

}) { (error) in
print(error.localizedDescription)
}

}

这是 homeViewController 中的 fetchAllPosts 函数

private func fetchAllPosts(){
authService.fetchAllPosts {(posts) in
self.postsArray = posts
self.postsArray.sort(by: { (post1, post2) -> Bool in
Int(post1.postDate) > Int(post2.postDate)
})

self.tableView.reloadData()
}
}

这是我的 swift 文件中的帖子结构:

struct Post {


var username: String!
var uid: String!
var postId: String!
var type: String
var postText: String
var postTit: String
var postPicUrl: String!
var postDate: NSNumber!
var ref: FIRDatabaseReference!
var key: String = ""

init(postId: String,postText: String, postTit:String, postDate:NSNumber, postPicUrl: String?, type:String, uid: String, key: String = ""){

self.postText = postText
self.postTit = postTit
self.postPicUrl = postPicUrl
self.type = type
self.uid = uid
self.postDate = postDate
self.postId = postId

}

init(snapshot: FIRDataSnapshot){

self.ref = snapshot.ref
self.key = snapshot.key
self.postId = (snapshot.value! as! NSDictionary)["postId"] as! String
self.type = (snapshot.value! as! NSDictionary)["type"] as! String
self.postPicUrl = (snapshot.value! as! NSDictionary)["postPicUrl"] as! String
self.postDate = (snapshot.value! as! NSDictionary)["postDate"] as! NSNumber
self.postTit = (snapshot.value! as! NSDictionary)["postTit"] as! String
self.uid = (snapshot.value! as! NSDictionary)["uid"] as! String
self.postText = (snapshot.value! as! NSDictionary)["postText"] as! String
}


func toAnyObject() -> [String: Any] {
return ["postId":self.postId,"type":self.type, "postPicUrl":self.postPicUrl,"postDate":self.postDate, "postTit":self.postTit,"uid": self.uid, "postText":self.postText,]
}
}

最佳答案

你用过这个吗?

    postRef.queryOrdered(byChild: "uid").queryEqual(toValue: yourUid).observe(.value, with: {
snapshot in

if let shot = snapshot {
let post = Post(snapshot: post as! FIRDataSnapshot)
}

}

这将返回您正在查找的数据。

关于swift - 如何过滤 Firebase 数据库中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42725095/

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