I’m a beginner in iOS development, teaching myself 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 questions and options from the API, but I’m having trouble with the answer checking part.
Here’s a simplified version of my code for fetching questions:
func getQuizData() {
let apiEndpoint = "YOUR_AIRTABLE_API_ENDPOINT"
let authToken = "YOUR_AUTH_TOKEN"
var apiRequest = URLRequest(url: URL(string: apiEndpoint)!)
apiRequest.addValue("Bearer \(authToken)", forHTTPHeaderField: "Authorization")
URLSession.shared.dataTask(with: apiRequest) { (data, response, error) in
guard let quizData = data else { return }
do {
let quizItems = try JSONDecoder().decode(QuizResponse.self, from: quizData)
DispatchQueue.main.async {
self.updateUI(with: quizItems)
}
} catch {
print("Error decoding data: \(error)")
}
}.resume()
}
My problem is with the answer checking function. When I try to access the API response data, it’s nil. I think I might need to fetch the data again, but I’m not sure how to structure this correctly. Any ideas on how to efficiently check answers against the Airtable data?
Storing quiz data locally is indeed a good approach. To implement this, declare a property in your view controller, for example, ‘private var quizItems: [QuizItem] = ’. In your ‘getQuizData()’ function, after decoding the JSON, assign the data to this property by doing something like ‘self.quizItems = quizItems.records’. Then, create a separate function for answer checking that compares the user’s answer with the correct answer stored in quizItems. This eliminates the need for repeated API calls. Also, ensure you handle cases where the quiz data might be empty or when there are network issues.
hey there! I’ve worked with airtable before. instead of fetching data every time u check an answer, try storing the quiz data locally after the initial fetch. u can use a property like var quizItems: [QuizItem]? and update it in getQuizData(). then access it for answer checking. hope this helps!
Having struggled with similar issues early on, I’ve since found that caching the quiz data locally really simplifies answer checking. In my experience, fetching the data once and storing it—perhaps in a dictionary keyed by unique question IDs—greatly improves performance by avoiding unnecessary API calls.
For example, I used something like:
var quizDataCache: [String: QuizItem] = [:]
// After decoding the response
for item in quizItems.records {
quizDataCache[item.id] = item
}
This method not only speeds up the app but also minimizes error handling related to network issues. Handling cases of empty or outdated caches is crucial to maintain a seamless experience.