I am trying to retrieve data from firebase and display into multiple buttons and label. After retrieving i am saving it into a dictionary. This is my model
import Foundation
import Firebase
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
}
}
}
My JSON
I tried some ways but it return me nil .I think coz of asynchronous firebase.
This is my code .
import Foundation
import UIKit
import Firebase
import FirebaseDatabase
class AnsweringQuestionViewController: UIViewController {
@IBOutlet weak var qLabel: UILabel!
@IBOutlet weak var buttonA: UIButton!
@IBOutlet weak var buttonB: UIButton!
@IBOutlet weak var buttonC: UIButton!
@IBOutlet weak var correctAnswer: UIButton!
//var buttons: [UIButton]! thinking of using button tags?
var ref: FIRDatabaseReference!
var questionModel : [QuestionModel] = []
override func viewDidLoad(){
super.viewDidLoad()
// FIRDatabase.database().persistenceEnabled = true
ref = FIRDatabase.database().reference()
db()
}
func db(){
ref.child("Science").observe(.value, with: {
snapshot in
for child in snapshot.children {
let user = QuestionModel.init(snapshot: (child as? FIRDataSnapshot)!)
self.questionModel.append(user)
}
self.qLabel.text = self.questionModel[0].Question
self.buttonA.setTitle("\(self.questionModel[0].CorrectAnswer)", for: UIControlState.normal)
}, withCancel: nil)
}
}
Pls bare with my code i am still learning. I don't have any idea where to go from here in displaying my data into multiple buttons and identifying which button is 'clicked' is the CorrectAnwer.
I would be very happy if you could reconstruct my code to a cleaner way if you want. Thank you :)