Swift + Firebase:使用对服务器的查询随机选择一组对象 [英] Swift + Firebase: randomly picking a group of objects using a query to the server

查看:36
本文介绍了Swift + Firebase:使用对服务器的查询随机选择一组对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Swift和Firebase作为后端为iOS构建一个测验应用程序.我希望能够进行查询以选择10个随机问题并将其返回.

I am building a quiz app for iOS using Swift and using Firebase as a backend. I want to be able to make a query that picks 10 random questions and returns them.

推荐答案

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

First of all for my answer you need to give each question a value like this:

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

之后,建议在您的Firebase规则中添加一个索引( firebase文档),如下所示:

After that it's recommended to add an index in your firebase rules (firebase docs) like this:

    {
      "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)
    })
}

实际的快速代码可能存在缺陷,对于特定于Firebase的代码,请查看

The actual swift code may be flawed and for the firebase specific code take a look at Ios documentation

这篇关于Swift + Firebase:使用对服务器的查询随机选择一组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆