从Firebase数据库中检索/读取数据

时间:2017-12-31 01:51:26

标签: swift firebase firebase-realtime-database

我正在使用此代码从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)
        }
    })

1 个答案:

答案 0 :(得分:1)

如果您的数据库只有projects/1以及您想要访问项目/ 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)