如何使用Swift 3从Firebase检索到数组?

时间:2017-03-14 08:10:17

标签: firebase swift3 firebase-realtime-database

我有这个firebase结构

enter image description here

{
  "English" : {
    "-Kf1-6xbGqxAgWEWkPMO" : {
      "CorrectAnswer" : "asdf",
      "OptionA" : "a1",
      "OptionB" : "b1",
      "OptionC" : "c1",
      "Question" : "Question1"
    },
    "-Kf9ap_0ja3rwEGPn-lz" : {
      "CorrectAnswer" : "fdas",
      "OptionA" : "a2",
      "OptionB" : "b2",
      "OptionC" : "C2",
      "Question" : "Question2"
    }
    ...//more questions
  },
   "AnotherSubject" : {
    "-Kf1-6xbGqxAgWEWkPMO" : {
      "CorrectAnswer" : "asdf",
      "OptionA" : "a1",
      "OptionB" : "b1",
      "OptionC" : "c1",
      "Question" : "Question1"
    },
    "-Kf9ap_0ja3rwEGPn-lz" : {
      "CorrectAnswer" : "fdas",
      "OptionA" : "a2",
      "OptionB" : "b2",
      "OptionC" : "C2",
      "Question" : "Question2"
    }
    ...//more questions
  },
  "Users" : {
    "E2Ym1qb0dIT8zARlLLxEOCheg4E3" : {
      "email" : "adsf@gmail.com",
      "name" : "asdf asdf"
    },
    "vL8p17oDFaUp0iJCQYNS0xgntyg2" : {
      "email" : "sdf@gmail.com",
      "name" : "sadfsd"
    },
    ...
  }
}

我如何检索这个"问题"并保存到像

这样的数组中
var question = ["Question1", "Question2",...], 

和这些"答案","选项A","选项B"进入var

var answer = [["Answer","a1","b1","c1"], ["Answer2","a2","b2","c2"],[...]]

非常感谢任何帮助。我知道有一百种方法可以做到这一点。获得相同结果的有效方法是一个巨大的帮助。

1 个答案:

答案 0 :(得分:0)

创建问题模型以将问题的问题和内容提取到数组中。将您的快照投射到Dictionary,然后获取值;

    class QuestionModel: NSObject {
         var CorrectAnswer: String!
         var Question: String!
         var optionA: String!
         var optionB: String!
         var optionC: String!

         init(snapshot: FIRDataSnapshot) {
            if let snapshotDict = snapshot.value as? Dictionary<String, Any> {
                CorrectAnswer = snapshotDict["CorrectAnswer"] as? String
                Question = snapshotDict["Question"] as? String
                optionA = snapshotDict["optionA"] as? String
                optionB = snapshotDict["optionB"] as? String
                optionC = snapshotDict["optionC"] as? String      
            }
        }
       }
回调中的

;

var questionModels : [QuestionModel] = []
        FIRDatabase.database().reference().child("English").observe(.value, with: {
            snapshot in

            for child in snapshot.children {
                let user = QuestionModel.init(snapshot: (child as? FIRDataSnapshot)!)
                self.questionModels.append(user)
            }


        })

您必须发送与FIRDatabase.database().reference().child("English")FIRDatabase.database().reference().child("AnotherSubject")等节点数一样多的请求。而且你不需要var answer = [["Answer","a1","b1","c1"], ["Answer2","a2","b2","c2"],[...]]。你拥有的问题数组将做同样的事情。你可以questionModels[0].CorrectAnswer或任何你想做的事情