I’m a beginner in iOS development learning Swift. I’m working on an English quiz app and want to use Airtable to store and fetch my quiz data. I’ve managed to get the questions and options from Airtable but I’m having trouble with the answer checking part.
Here’s a simplified version of my code for fetching questions:
func getQuizData() {
let endpoint = "airtable_api_endpoint"
let token = "your_api_token"
var apiRequest = URLRequest(url: URL(string: endpoint)!)
apiRequest.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
URLSession.shared.dataTask(with: apiRequest) { (responseData, _, error) in
guard let data = responseData else { return }
do {
let quizInfo = try JSONDecoder().decode(QuizResponse.self, from: data)
DispatchQueue.main.async {
self.updateUI(with: quizInfo)
}
} catch {
print("Error: \(error)")
}
}.resume()
}
My problem is with the answer checking function:
func isAnswerCorrect(_ userChoice: String) -> Bool {
// This line causes a crash because 'quizData' is nil
return userChoice == quizData.records[currentQuestionIndex].fields.correctAnswer
}
How can I properly check the user’s answer against the correct answer from Airtable? Do I need to make another API call or is there a better way to handle this? Any help would be appreciated!
From my experience working with Airtable and iOS, I’d recommend a slightly different approach. Instead of making multiple API calls, fetch all the quiz data at once and store it locally. This reduces network requests and improves app performance.
Create a QuizManager class to handle data fetching and answer checking:
class QuizManager {
private var quizData: [QuizQuestion] = []
func fetchQuizData(completion: @escaping (Result<Void, Error>) -> Void) {
// Your API call here
// Parse and store data in quizData array
}
func checkAnswer(_ userChoice: String, forQuestionIndex index: Int) -> Bool {
guard index < quizData.count else { return false }
return userChoice == quizData[index].correctAnswer
}
}
This structure separates concerns and makes your code more maintainable. It also ensures data is available before checking answers, avoiding the nil crash you encountered.
I’ve faced similar challenges when working with Airtable in my iOS projects. Here’s what worked for me:
Instead of checking the answer immediately, I’d suggest storing the fetched data in a property of your view controller. Then, implement a separate method for answer checking that you can call when the user selects an option.
Something like this:
class QuizViewController: UIViewController {
var quizData: QuizResponse?
func getQuizData() {
// Your existing API call code here
// In the completion handler:
self.quizData = quizInfo
self.updateUI(with: quizInfo)
}
func checkAnswer(_ userChoice: String) -> Bool {
guard let quizData = quizData else {
print("Quiz data not loaded yet")
return false
}
return userChoice == quizData.records[currentQuestionIndex].fields.correctAnswer
}
}
This approach ensures you’re not trying to access the data before it’s loaded. Remember to call getQuizData() when your view controller loads, and use checkAnswer(_ when the user submits their choice.
hey mate, i think ur issue is with timing. looks like ur trying to access quizData before it’s loaded from the API. try moving the answer checking logic into the completion handler of ur API request. that way u’ll have the data ready when u need it. hope this helps!