问题描述
我是 iOS 新手,自学 swift,目前在 API 部分,想在我的英语测验项目中使用 Airtable,我已经知道如何获取数据并显示问题/选项,
@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,alpha: 1)
self.optionC.backgroundColor = #colorLiteral(red: 0.01954602264,alpha: 1)
self.optionD.backgroundColor = #colorLiteral(red: 0.01954602264,alpha: 1)
print(qAndA.records[self.questionIndex].fields.question)
} catch {
print(error)
}
}.resume()
}
但是在检查答案时,我卡住了......
func checkAnswer(userAnswer: String) -> Bool {
if userAnswer == response.records[self.questionIndex].fields.answer {
scoreNumber += 1
return true
} else {
return false
}
}
这将得到一个致命错误,因为响应(我为 API 制作的结构)被发现为零,我知道也许我需要再次请求以获取答案并与用户输入匹配,但我不知道如何检查我的答案...
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)",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
}
}
}
}
I have finished fetch data and show it on the labels/buttons
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)