【问题标题】:Firebase snapshot to an array of objectsFirebase 快照到对象数组
【发布时间】:2020-10-06 15:10:33
【问题描述】:

我是 Swift 和 Firebase 的新手,我正在构建一个应用程序,但我遇到了一个非常困难的时期(而且我正在打印数据,这似乎真的很简单......)来转换数据(来自 Firebase 实时数据库)我检索到一组用户...

我希望能够做到:

for user in users {
  print(user.name)
}

输出:

"Bob"
"John"
...

基本上有一个包含对象的简单数组。

这就是我检索数据的方式:

let data = Database.database().reference().child("dbusers")
    
    data.child("users").observeSingleEvent(of: .value) { (snapshot) in
        print(snapshot)
    }

这是上面打印语句的输出:

Snap (users) {
    0 =     {
        coeff1 = "";
        coeff2 = "";
        id = "";
        userLogo = "";
        userName = "";
        userUrl = " ";
    };
    1 =     {
        coeff1 = 1;
        coeff2 = 1;
        id = 1;
        userLogo = bobbyLogo;
        userName = Bob;
        userUrl = urlOfBobby;
    };
    2 =     {
        coeff1 = 1;
        coeff2 = 1;
        id = 2;
        userLogo = mariaLogo;
        userName = Maria;
        userUrl = urlOfMaria;
    };
    3 =     {
        coeff1 = 1;
        coeff2 = 1;
        id = 3;
        userLogo = johnLogo;
        userName = John;
        userUrl = urlOfJohn;
    };
    4 =     {
        coeff1 = 1;
        coeff2 = 1;
        id = 4;
        userLogo = jamesLogo;
        userName = James;
        userUrl = urlOfJames;
    };
    5 =     {
        coeff1 = 1;
        coeff2 = 1;
        id = 5;
        userLogo = jackLogo;
        userName = Jack;
        userUrl = urlOfJack;
    };
    6 =     {
        coeff1 = 1;
        coeff2 = 1;
        id = 6;
        userLogo = nikolasLogo;
        userName = Nikolas;
        userUrl = urlOfNikolas;
    };
}

【问题讨论】:

    标签: swift firebase firebase-realtime-database


    【解决方案1】:

    由于您正在阅读/dbusers/users,因此您将获得包含所有用户的快照。您需要遍历snapshot 的子节点以获取每个单独的用户,然后可以获取他们的userName 属性。

    类似这样的:

    let data = Database.database().reference().child("dbusers")    
    
    data.child("users").observeSingleEvent(of: .value) { (snapshot) in
        for childSnapshot in snapshot.children.allObjects as! [DataSnapshot] {
            print(childSnapshot.key) // prints the key of each user
            print(childSnapshot.childSnapshot(forPath:"userName").value) // prints the userName property
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-25
      • 1970-01-01
      • 1970-01-01
      • 2016-10-28
      • 2018-06-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多