Swift + Firebase:使用查询随机选择一组对象到服务器

时间:2016-02-20 14:46:15

标签: ios swift firebase

我正在使用Swift构建一个针对iOS的测验应用,并使用Firebase作为后端。我希望能够提出一个选择10个随机问题并返回它们的查询。

enter image description here

1 个答案:

答案 0 :(得分:3)

首先,对于我的回答,你需要给每个问题一个这样的值:

    {
      "question1": {
        "question" : "Do you know swift",
        "answer" : "Nope",
        "value": 1
      },
      "question2": {
        "question" : "Do you know firebase",
        "answer" : "A bit",
        "value" : 2
      }
    }

之后,建议在firebase规则(firebase docs)中添加索引,如下所示:

    {
      "rules": {
        "questions": {
          ".indexOn": ["value"]
        }
      }
    }

接下来是快速部分:

//Use a for loop to get 10 questions
for _ in 1...10{
  //generate a random number between 1 and the amount of questions you have
  var randomNumber = Int(arc4random_uniform(amountOfQuestions - 1)) + 1

  //The reference to your questions in firebase (this is an example from firebase itself)
  let ref = Firebase(url: "https://dinosaur-facts.firebaseio.com/dinosaurs")
    //Order the questions on their value and get the one that has the random value
  ref.queryOrderedByChild("value").queryEqualToValue(randomNumber)
    .observeEventType(.ChildAdded, withBlock: {
      snapshot in
        //Do something with the question
        println(snapshot.key)
    })
}

实际的swift代码可能存在缺陷,对于firebase特定代码,请查看Ios documentation