【问题标题】:Retrieve / read data from Firebase database从 Firebase 数据库中检索/读取数据
【发布时间】:2017-12-31 23:49:02
【问题描述】:

我正在使用此代码从 Firebase 数据库中检索数据。但是,我一次只能提取一个变量。您能帮我找到一种方法来提取其他人(学生姓名、职称等)并将它们保存到对象 arrayList 中吗?

{
  "projects" : [ 
     1, {
        "answer1" : false,
        "answer2" : true,
        "answer3" : true,
        "campus" : "Science Academy",
        "category" : "LifeScience",
        "question1" : "This is question 1",
        "question2" : "This is question 2",
        "question3" : "This is question 3",
        "student1" : "john",
        "student2" : "Kyle",
        "title" : "Amazon Forest"
        }
   ]
 }


var ref : DatabaseReference?
var handle : DatabaseHandle?


    ref = Database.database().reference()
    handle = ref?.child("projects").child("1").child(question1).observe(.value, with: { (snapshot) in
        if let question = snapshot.value as? String {
            print(question)
        }
    })

【问题讨论】:

  • 我不明白你为什么需要访问他的数据库@KhawarIslam。他的数据库结构包含在问题中
  • 我不懂swift,所以帮不上什么忙。看看Firebase Documentation
  • 我不需要访问数据库,我只需要 URL。因为我想一个一个地迭代元素。
  • 您是在问如何访问 1 节点的子值吗?所以你想用键 answer1、category 等获取值吗?如果是这样,第一个问题是您似乎正在使用数组在 Firebase 中存储数据,这可能会导致许多其他问题。其次,您包含的代码只会读取 question1 键的值。哦。而且您不需要提供您的数据库 URL - 这是对这个问题的愚蠢要求。

标签: swift firebase firebase-realtime-database


【解决方案1】:

如果您的数据库有更多 projects/1 并且您想要访问 projects/1-2-3-4 等,那么您需要执行以下操作:

    let reference = Database.database().reference()
    reference.child("projects").observe(.childAdded, with: { (snapshot) in

        let key = snapshot.key // THIS WILL GET THE PROJECT THAT IT'S IN. 1, 2, 3, 4 etc.

        guard let dictionary = snapshot.value as? [String: AnyObject] else { return }

        let answer1 = dictionary["answer1"] as? Bool
        let campus = dictionary["campus"] as? String

    }, withCancel: nil)

如果您想简单地获取 project/1 中的所有值而不仅仅是问题,您需要执行以下操作:

    let reference = Database.database().reference()
    reference.child("projects").child("1").observeSingleEvent(of: .value, with: { (snapshot) in

        let key = snapshot.key // THIS WILL GET THE PROJECT THAT IT'S IN. 1, 2, 3, 4 etc.

        guard let dictionary = snapshot.value as? [String: AnyObject] else { return }

        let answer1 = dictionary["answer1"] as? Bool
        let campus = dictionary["campus"] as? String

    }, withCancel: nil)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-17
    • 2021-10-16
    • 2018-12-22
    相关资源
    最近更新 更多