gpt4 book ai didi

swift - 将项目从 firebase 加载到 pickerview 的问题

转载 作者:行者123 更新时间:2023-11-28 15:45:30 25 4
gpt4 key购买 nike

我已经成功创建了一个 QuestionModel 类,它从 firebase 中检索项目,例如问题、答案字符串和正确的问题。然而,我现在很难让这些项目从另一个类(class)进入选择器 View 。名为 QuestionsViewController 的类是我在使用问题类从中检索数据方面遇到问题的地方。 QuestionModel 类包含从 firebase 检索数据。我在 QuestionsViewController 类的整个代码中都遇到了错误的执行错误。这主要发生在尝试在 pickverview 和 pickerview 函数的代码之前设置 itemlabel 文本时。

import Foundation
import Firebase
import FirebaseDatabase
import FirebaseAuth
import CoreData

class QuestionList
{
//properties
public static var Username: String = ""
private static var quiz = [Question]()

static func getDummyQuestions()->[Question]
{
//create some dummy data for the model
var ref: FIRDatabaseReference!
var refHandle: UInt!
ref = FIRDatabase.database().reference() //reference

refHandle = ref.child("Questions").child("Q1").observe(.value, with: { (snapshot)in
if let dataDict = snapshot.value as? [String: Any] {

if let quest = dataDict["Question"] as? String,
let Answers = dataDict["Answers"] as? [String],
let Correct = dataDict["Correct"] as? Int {
quiz.append(Question(q: quest, a: Answers, c: Correct))
}
print (dataDict)
}
})
return quiz
}
}


class Question {
var quest:String
var answers:[String]
var correct:Int

init(q: String, a:[String], c:Int)
{
quest = q
answers = a
correct = c
}

func isCorrectQuestion(itemSelected: String)->Bool {
if (itemSelected == answers[correct]) {
return true
} else {
return false
}
}
}

import UIKit
import Firebase
import FirebaseAuth

class QuestionsViewController: UIViewController, UIPickerViewDelegate {

@IBOutlet weak var usernamelabel: UILabel! //sets username label
@IBOutlet weak var Next: UIButton! //next button
@IBOutlet weak var itemLabel: UILabel! //item user has selected
@IBOutlet weak var Question: UILabel! //sets question label
@IBOutlet weak var pickerview: UIPickerView! //sets picker view

public var totalQuestions: Int = 0 //sets total question to 0
public var currentQuestion = 0 //sets current question to 0
public var totalCorrect: Int = 0 //sets totalcorrect to 0
var itemSelected: String = "" //item selected
var LabelText = String()
let Exam = QuestionList() //uses the questions class for instances
var Questions = QuestionList.getDummyQuestions()

var ref: FIRDatabaseReference!
var refHandle: UInt!

override func viewDidLoad() {
super.viewDidLoad() //when the app is loaded

ref = FIRDatabase.database().reference() //reference
refHandle = ref.child("Questions").observe(.value, with: { (snapshot)in
let dataDict = snapshot.value as! [String: AnyObject]
print (dataDict)
})
usernamelabel.text = LabelText //username

pickerview.delegate = self

itemLabel.text = "" //loads the item label of whats selected
itemSelected = QuestionList.getDummyQuestions()[currentQuestion].answers[0] //initially when loaded first item is selected
Question.text = QuestionList.getDummyQuestions()[currentQuestion].quest
}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1 //return one component from the picker
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
return QuestionList.getDummyQuestions()[currentQuestion].answers.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{
return QuestionList.getDummyQuestions(). [currentQuestion].answers[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){

itemSelected = QuestionList.getDummyQuestions(). [currentQuestion].answers[row]
}

@IBAction func NextAction(_ sender: Any){

currentQuestion = currentQuestion + 1 //moves onto next question and increments

if (QuestionList.getDummyQuestions()[currentQuestion].isCorrectQuestion(itemSelected: itemSelected)) {
totalCorrect += 1
itemLabel.text = String(totalCorrect) + "/" + String(totalQuestions)
}

if(currentQuestion < QuestionList.getDummyQuestions().count) {
pickerview.reloadAllComponents()
itemSelected = QuestionList.getDummyQuestions()[currentQuestion].answers[1]
Question.text = QuestionList.getDummyQuestions() [currentQuestion].quest
} else {
pickerview.isHidden = true
Question.text = "You have finished"
Next.isHidden = true
}
}

最佳答案

Firebase 函数不会(也不应该)返回值,因为它们是异步的。

因此返回测验行大部分时间都会失败,因为它会在 Firebase 有时间从服务器检索数据之前尝试返回数据。

使用 Firebase 编码时,数据仅在函数后面的闭包内有效。因此,例如,这是不该做的事情:

func someFunc() {
ref.child("Questions").child("Q1").observe(.value, with: { snapshot in
print(snap)
})

print(snap) //this will not print the snap as this line executes *before* the closure
}

所以要以正确的方式去做;从 Firebase 检索数据,填充数组并刷新所有在闭包内的 TableView 。

static func populateArrayAndRefreshTableView()
{
var ref: FIRDatabaseReference!= FIRDatabase.database().reference()
let questionsRef = ref.child("Questions")

questionsRef.child("Q1").observeSingleEvent(of: .value, with: { snapshot in
if let dataDict = snapshot.value as? [String: Any] {
let quest = dataDict["Question"] as? String,
let Answers = dataDict["Answers"] as? [String],
let Correct = dataDict["Correct"] as? Int {
self.quizArray.append(Question(q: quest, a: Answers, c: Correct))
self.tableView.reloadData()
}
})
}
}

另请注意,原始代码使用的是 observe(.value)。这将使观察者附加到 ref,如果问题发生变化,将调用代码。它看起来不应该是这样的行为,所以使用 observeSingleEvent 将调用它一次而不添加观察者。

最后 - 您可能需要重新考虑节点在您的结构中的命名方式。将节点名称键与其包含的数据分离通常是最佳做法。

questions
-UYiuokoksokda
question: "What significant contribution to bioengineering was made on the Loonkerian outpost on Klendth?"
correct_answer: answer_1
answers:
answer_0: "Left handed smoke shifter"
answer_1: "The universal atmospheric element compensator"
answer_2: "Warp coil nullification amplifier"
answer_3: "H.A.L. 9000"
-YY8jioijasdjd
question: "What is Kiri-kin-tha's first law of metaphysics?"
correct_answer: answer_2
answers:
answer_0: "No matter where you go, there you are"
answer_1: "Only people with sunroofs use them"
answer_2: "Nothing unreal exists"
answer_3: "Gravity is heavy"

key UYiuokoksokda 是使用 childByAutoId() 创建的。

如果您需要查询答案,您甚至可能希望将它们非规范化到它们自己的节点中,并使用问题键作为答案的节点键,或者保留一个带有问题键的子节点。

关于swift - 将项目从 firebase 加载到 pickerview 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43131604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com