I'm new to SwiftUI and trying to build a simple single-player Quiz app. I started by following this tutorial and then tried to continue on my own. Currently, the questions are hardcoded in my ViewModel but I'd like to change it to fetching from a local JSON file instead. Anyone that can point me in the right direction?
Here's a part of my ViewModel with the questions as static data:
extension GameManagerVM {
static var questions = quizData.shuffled()
static var quizData: [QuizModel] {
[
QuizModel(
id: 1,
question: "Question title 1",
category: "Sport",
answer: "A",
options: [
QuizOption(id: 11, optionId: "A", option: "A"),
QuizOption(id: 12, optionId: "B", option: "B"),
QuizOption(id: 13, optionId: "C", option: "C"),
QuizOption(id: 14, optionId: "D", option: "D")
]
),
...
}
}
Here's a test I did, but I get the error that Xcode can't decode it. I replace the above code with this:
extension GameManagerVM {
static var questions = quizData.shuffled()
static var quizData: [QuizModel] = Bundle.main.decode("quizquestions2022.json")
}
And here's the JSON.
[
{
"id": "1",
"question": "Question title 1",
"category": "Sport",
"answer": "A",
"options": [
{
"id": "1001",
"optionId": "A",
"option": "A"
},
{
"id": "1002",
"optionId": "B",
"option": "B"
},
{
"id": "1003",
"optionId": "C",
"option": "C"
},
{
"id": "1004",
"optionId": "D",
"option": "D"
}
]
},
]
Here are my models
struct Quiz {
var currentQuestionIndex: Int
var quizModel: QuizModel
var quizCompleted: Bool = false
var quizWinningStatus: Bool = false
var score: Int = 0
}
struct QuizModel: Identifiable, Codable {
var id: Int
var question: String
var category: String
var answer: String
var options: [QuizOption]
}
struct QuizOption: Identifiable, Codable {
var id: Int
var optionId: String
var option: String
var isSelected: Bool = false
var isMatched: Bool = false
}