【问题标题】:swift showing posts from all firebase users快速显示所有 firebase 用户的帖子
【发布时间】:2017-03-11 03:19:14
【问题描述】:

我需要创建一个使用 firebase 作为后端的 UISearchController。我目前在 firebase 中有两个用户。一位用户发表了一篇文章,另一位发表了四篇文章。我希望能够在我的数据库中搜索所有书籍的标题(即五本书)。但是,到目前为止,我只能搜索当前登录用户上传的书籍。下面是我的数据库的截图和我的代码目前的截图。

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

}

【问题讨论】:

    标签: ios swift firebase firebase-realtime-database


    【解决方案1】:

    您将需要一个名为 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/};
           }
    
     }
    

    修改“图书”部分的安全规则,使所有经过身份验证的用户都可以看到。

    {
     "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',安全规则将与 'Users_books' 相同,并在 'Users' 父节点下附加每个用户的详细信息他们的 uid 作为他们的密钥。

    【讨论】:

      猜你喜欢
      • 2017-04-02
      • 1970-01-01
      • 1970-01-01
      • 2022-08-13
      • 1970-01-01
      • 1970-01-01
      • 2012-10-02
      • 2017-04-05
      • 2022-01-11
      相关资源
      最近更新 更多