I'm new to iOS, self-learning swift, currently on API section and want to use Airtable for my English quiz project, I have figured out how to fetch data and show questions/options,
@objc func fetchQandA() {
let urlStr = "https://api.airtable.com/v0/appCwgj8Lq47t3SAT/QandA?maxRecords=10&view=Grid%20view"
let apiKey = "apiKey"
let url = URL(string: urlStr)
var request = URLRequest(url: url!)
request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
URLSession.shared.dataTask(with: request) { (data, response, error) in
let decoder = JSONDecoder()
guard let data = data else { return }
do {
let qAndA = try decoder.decode(Response.self, from: data)
DispatchQueue.main.async {
self.numberOfQuestion.text = "Question \(self.questionIndex+1)"
self.questionLabel.text = qAndA.records[self.questionIndex].fields.question
self.optionA.setTitle(qAndA.records[self.questionIndex].fields.optionA, for: .normal)
self.optionB.setTitle(qAndA.records[self.questionIndex].fields.optionB, for: .normal)
self.optionC.setTitle(qAndA.records[self.questionIndex].fields.optionC, for: .normal)
self.optionD.setTitle(qAndA.records[self.questionIndex].fields.optionD, for: .normal)
}
self.optionA.backgroundColor = #colorLiteral(red: 0.01954602264, green: 0.266705811, blue: 0.2860710323, alpha: 1)
self.optionB.backgroundColor = #colorLiteral(red: 0.01954602264, green: 0.266705811, blue: 0.2860710323, alpha: 1)
self.optionC.backgroundColor = #colorLiteral(red: 0.01954602264, green: 0.266705811, blue: 0.2860710323, alpha: 1)
self.optionD.backgroundColor = #colorLiteral(red: 0.01954602264, green: 0.266705811, blue: 0.2860710323, alpha: 1)
print(qAndA.records[self.questionIndex].fields.question)
} catch {
print(error)
}
}.resume()
}
but when it comes to checking answer, I got stuck...
func checkAnswer(userAnswer: String) -> Bool {
if userAnswer == response.records[self.questionIndex].fields.answer {
scoreNumber += 1
return true
} else {
return false
}
}
This will get a fatal error since response(struct that I made for the API) is found nil, I know maybe I need to request again to fetch answer and match with user input, but I can't figure out how to check my answer...
func checkAnswer(userAnswer: String) -> Bool {
let urlStr = "https://api.airtable.com/v0/appCwgj8Lq47t3SAT/QandA?maxRecords=10&view=Grid%20view"
let apiKey = "apiKey"
let url = URL(string: urlStr)
var request = URLRequest(url: url!)
request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
URLSession.shared.dataTask(with: request) { (data, response, error) in
let decoder = JSONDecoder()
if let data = data,
let answer = try decoder.decode(Response.self, from: data) {
if userAnswer == answer.records[questionIndex].fields.answer {
scoreNumber += 1
return true
} else {
return false
}
}
}
}