How Do I Return This JSON Output Out of The "Do" Call In Swift?

I’ve spent the last few hours working on retrieving the contents of a JSON and puts it into an array. Now that I’ve finally got it, I have no idea how to get the variable "students" that contains the array. I want to be able to return this variable back to the viewDidLoad function. Can you please help?

class ViewController: UIViewController {   struct Student: Decodable {     let Name: String?     let Gender: String     let SRT, RST, Accuracy: Double     let AttentionLevel: Int     let FavoriteSubject, LeastFavoriteSubject: String  }   struct Student: Decodable {     let Name: String     let Score: Int } override func viewDidLoad() {     super.viewDidLoad()      getJSONFromOnline()       }  func getJSONFromOnline(){     let jsonURLString = "insert example URL String here" //(I'm using a GitHub Pages site to host the students' data)          let url = URL(string: jsonURLString)          URLSession.shared.dataTask(with: url!){         (data, response, err) in                  guard let data = data else {return}                  do {             let students = try JSONDecoder().decode([Student].self, from: data)             //How do I get this ^^^ variable back to the viewDidLoad function?         }                  catch let jsonErr{             print("error serializing", jsonErr)         }     }.resume()  }  } 
Add Comment
1 Answer(s)

Add an @escaping completion block to the getJSONFromOnline method and use the closure block the get the students in viewDidLoad.

class ViewController: UIViewController {     //...     override func viewDidLoad() {         super.viewDidLoad()          getJSONFromOnline { students in             print("got students", students)         }     }      func getJSONFromOnline(completion: @escaping ([Student]) -> Void) {         //...         let students = try JSONDecoder().decode([Student].self, from: data)         completion(students)         //...     } } 

Add-on: It would be better to name the method some a bit more specific, like getStudents or fetchStudents. Also, move the struct Student declaration outside of the ViewCotroller.

Answered on August 4, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.