swift显示所有firebase用户的post

我需要使用firebase作为后端创建一个UISearchController。 我目前在firebase中有两个用户。 一个用户发了一个post,另一个发了四个post。 我希望能够搜索我的数据库中的所有书籍的标题(五个)。 但是,截至目前,我只能搜索当前用户上传的书籍。 下面是我的数据库看起来像什么以及我的代码目前是什么样的截图。

这是我的数据库的截图

databaseRef.child("posts").child(userID!).observe(.childAdded, with: { (snapshot) in let key = snapshot.key let snapshot = snapshot.value as? NSDictionary snapshot?.setValue(key, forKey: "uid") if(key == self.loggedUser?.uid) { print("same as logged in user") } else { self.usersArray.append(snapshot) self.followUsersTableView.insertRows(at: [IndexPath(row:self.usersArray.count-1,section:0)], with: UITableViewRowAnimation.automatic) } }) { (error) in print(error.localizedDescription) } } 

您将需要一个名为Books的不同父节点: –

现在您的JSON是这样的: –

 posts : { userID1 : { BOOK_11_ID : {.....} }; userID2 : { BOOK_21_ID : {.....}, BOOK_22_ID : {.....}, BOOK_23_ID : {.....}, BOOK_24_ID : {.....}, } } 

您必须将数据库JSON结构修改为: –

  posts : { Users_books :{ userID1 : { BOOK_11 : true // Value 'true' means that this user // has subscribed or bought this book or whatever }; userID2 : { BOOK_21 : true, BOOK_22 : true, BOOK_23 : true, BOOK_24 : true, } }, Books:{ BOOK_11_ID : {/Book details/}; BOOK_21_ID : {/Book details/}; BOOK_22_ID : {/Book details/}; BOOK_23_ID : {/Book details/}; BOOK_24_ID : {/Book details/}; } } 

修改“预订”部分的安全规则,使所有经过身份validation的用户都可以看到。

 { "rules" :{ "Users_books" : { ".write" : "auth != null && auth.uid === $uid", // Will allow only the user to make any change within its node and no-one else ".read": "auth != null && auth.uid === $uid" }, "Books" : { ".write" : "auth != null", // Will allow all the users that are authenticated to your app to access every books detail. ".read" : "auth != null" } } } 

现在你要做的是: –

1)如果是创建该书的用户; 然后将书籍详细信息存储在书籍uid下的父节点“Books”中,并在users节点中将book_ID的值设置为true。

2)如果数据库都是后端,即你输入它; 每当用户订阅或购买书籍时,只需获取该书的uid并在该用户的部分中将其设置为true。

PS :总是扇出你的数据库; 它更容易从它搜索。虽然我很确定你会想在不久的将来存储用户的一些个人细节,所以这只是另一个节点。 将其命名为“用户” ,安全规则将与“Users_books”相同,并在“用户”父节点下附加每个用户的uid作为其密钥的详细信息。