Swift-从Firebase读取数据(实时数据库)

时间:2019-06-28 07:02:46

标签: json swift firebase firebase-realtime-database

在Xcode开发中是全新的。

我在Firebase中创建了以下数据库:

{
  "Bicycle" : {
    "BMX" : {
      "image" : "bmx.png",
      "text" : "BMX ..."
    },
    "Dirt jumping" : {
      "image" : "dirtjumping.png",
      "text" : "Dirt jumping..."
    }
  },
  "Running" : {
    "Half-marathon" : {
      "image" : "halfmarathon.png",
      "text" : "Half-marathon ..."
    },
    "Marathon" : {
      "image" : "marathon.png",
      "text" : "Marathon ..."
    }
  }
}

现在,我想在第一个TableViewController中显示“自行车”和“正在运行”。

当我尝试以下代码时:

var ref: DatabaseReference!
ref = Database.database().reference()

ref.child("sports").observeSingleEvent(of: .value) { snapshot in
    print(snapshot.childrenCount) // I got the expected number of items
    for case let rest as DataSnapshot in snapshot.children {
        print(rest.children)
    }
}

我得到以下输出:

2
<FTransformedEnumerator: 0x6000038b40a0>
<FTransformedEnumerator: 0x6000038b40a0>

也许你可以给我一个很好的提示。

亲切的问候, 毁灭之网

2 个答案:

答案 0 :(得分:1)

获取snapshot.value作为字典,并从字典中获取详细信息

ref.child("sports").observeSingleEvent(of: .value, with: { snapshot in
    if let sports = snapshot.value as? [String: Any] { 
        for (title, details) in sports {
            print(title)//Bicycle
            print(details)//["BMX" : ["image" : "bmx.png", "text" : "BMX ..."], "Dirt jumping" : ["image" : "dirtjumping.png","text" : "Dirt jumping..."]]
        }
    }
}) { (error) in
    print(error.localizedDescription)
}

答案 1 :(得分:0)

您可以使用snapshot.valueInExportFormat()以字典格式获取数据。