class QuizzesModel{
var quizzes = [Quizz]()
func dameQuizzes(theURL:String){
let url = URL(string: theURL)
var quizzes = [Quizz]()
let task = URLSession.shared.dataTask(with:url!) { (data, response, error) in
do {
let parseData = try JSONSerialization.jsonObject(with: data!) as! [String:AnyObject]
if let preguntas = parseData["quizzes"] as? NSArray{
for x in (preguntas as? [[String:Any]])!{
var quizz = Quizz(image: "", question: "", tips: [""])
if let adjuntos = x["attachment"] as? NSDictionary{
if let urlImagen = adjuntos["url"] as? String{
quizz.image = urlImagen
}
}
if let question = x["question"] as? String{
quizz.question = question
}
if let pistas = x["tips"] as? NSArray{
quizz.tips = pistas
}
quizzes.append(quizz)
}
}
} catch let error as NSError{
print(error)
}
print(quizzes[0].question)
}
print(quizzes[0].question)
task.resume()
}
}
代码末尾的第一个 print(quizzes [0] .question)有效,但下一个不起作用,在 let task = URLSession.shared.dataTask( with:url!){
,因此我们无法将测验附加到测验数组中并在此方法之外使用它们。
我将非常感谢您的帮助:)