Reputation: 29
This might be a very easy question (sorry!).
I would like to links a mySQL database to a Quiz App in Swift 4. Therefore I connected to a service.php and got the information with decodable.
How can I access this information to show in a label? Do I have to make a new Array and append the objects?
import UIKit
struct Question: Codable {
let id: String?
let frage: String?
let antwort1: String?
let antwort2: String?
let antwort3: String?
let antwort4: String?
let correct: String?
let notiz: String?
let lernsektorID: String?
let lerneinheitID: String?
let lernbereichID: String?
let schwierigkeitID: String?
let redakteur: String?
let createdAt: String?
enum CodingKeys: String, CodingKey {
case id = "ID"
case frage = "Frage"
case antwort1 = "Antwort1"
case antwort2 = "Antwort2"
case antwort3 = "Antwort3"
case antwort4 = "Antwort4"
case correct = "Correct"
case notiz = "Notiz"
case lernsektorID = "LernsektorID"
case lerneinheitID = "LerneinheitID"
case lernbereichID = "LernbereichID"
case schwierigkeitID = "SchwierigkeitID"
case redakteur = "Redakteur"
case createdAt = "created_at"
}
}
var fragen = [Question]()
let url = "https://redaktion.pflegonaut.de/service.php"
let urlObj = URL(string: url)
URLSession.shared.dataTask(with: urlObj!) { (data, response, error) in
do {
self.fragen = try JSONDecoder().decode([Question].self, from: data!)
// can I use .append() here?
// maybe in a for loop?
} catch {
print(error)
}
}.resume()
So I can use the elements like:
//
// let randomizedQuestion = fragen.frage.randomElement()
//
// questionOutlet.text = randomizedQuestion
Thanks!
Upvotes: 0
Views: 235
Reputation: 285069
// NECESSARY? var QuestionBankJson: [QuestionJson] { var questionListJson = [QuestionJson]() }
No, just declare one array and name the struct simply Question
var questions = [Question]()
and assign
do {
self.questions = try JSONDecoder().decode([Question].self, from: data!)
print(self.questions[1].Frage!)
} catch {
print(error) // never print something meaningless like "we got an error"
}
Notes:
CodingKeys
.Codable
errors. Print always the error
instance.Date
.Upvotes: 1