【问题标题】:Firebase Swift syntaxFirebase Swift 语法
【发布时间】:2017-01-17 22:09:11
【问题描述】:

谁能帮我把它从 JavaScript 转换成 Swift 3 语法?

我正在尝试获取特定用户拥有的所有客户端。 我将客户端保存在他们自己的节点中,然后我在每个用户中都有一个客户端 ID 列表。

我相信这段代码会起作用,因为它来自的指南中描述了类似的情况,数据以相同的方式组织,但它不是快速的语法,尤其是 .on 和 .once。

var usersREF =
  new Firebase("https://awesome.firebaseio-demo.com/users");
var clientsREF =
  new Firebase("https://awesome.firebaseio-demo.com/clients");
var currentUsersClients = userREF.child("userID").child("comments");
currentUsersClients.on("child_added", function(snap) {
  clientsREF.child(snap.key()).once("value", function() {
    // Render the clients on the link page.
  ));
});

这是 Firebase 上的数据结构:

我想其他方法可能是获取当前用户的客户端 ID,然后调用所有客户端。通过 clientID 过滤它们。

或者

获取当前用户的 clientID,然后遍历它们,使用该 ID 对每个单独的客户端进行特定调用。

我只是不知道在 for 循环中多次调用 firebase 是否是不好的做法。或者更糟糕的是,要提取比必要更多的数据,然后对其进行过滤。

感谢您的帮助!

【问题讨论】:

  • 这真的不是一个代码编写服务,所以最好尝试编写代码并让我们知道你在哪里运行信息困难。请查看How to ask a question。此外,将来,请将您的 Firebase 结构发布为文本,而不是图像 - 这样它就可以搜索,我们在回答时不必重新输入它。在这种情况下,它非常简单,所以我发布了一个快速答案。

标签: ios firebase swift3 firebase-realtime-database


【解决方案1】:

这将根据您的结构获取 uid_0 的客户端

    let userRef = ref.child("users/uid_0")
    userRef.observeSingleEvent(of: .value, with: { snapshot in

        let userDict = snapshot.value as! [String:AnyObject]
        let clientsDict = userDict["clients"] as! [String:AnyObject]

        for client in clientsDict {
            let clientId = client.key
            print(clientId)
        }
    })

【讨论】:

    【解决方案2】:

    使用此示例代码获得您想要的结果

    func getUsers(forUserID userID: String, completion: @escaping (User) -> Swift.Void, failure: @escaping () -> ()) {
            if Auth.auth().currentUser != nil {
                Database.database().reference().child("users").child(userID).observe(.childAdded, with: { (snapshot) in
                    if snapshot.exists() {
                        let receivedMessage = snapshot.value as! [String: Any]
    
                        let name = receivedMessage["name"] as? String ?? ""
                        let id = receivedMessage["id"] as? Double ?? 0.0
                        let profileurl = receivedMessage["url"] as? String ?? ""
    
                        completion(User(name: name, id: id, url: url))
                    } else {
                        failure()
                    }
                })
            } else {
                failure()
            }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-02
      • 2018-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多