0

the people if let seems to print the json people[0].login fine but users is empty which I need to store the json so I can use it elsewhere in the app. I want the users var to get populated so it can actually be useful to me and not crash because there is nothing when I try to use it on the table view in the view controller. I can't use people outside of the scope of the if let.

import Foundation


final class UsersListViewModel {
  var users = [Users]()

  init() {
    fetchData()
  }
  func fetchData() {
        let url = URL(string: "https://api.github.com/users")!

        URLSession.shared.dataTask(with: url) { data, response, error in
            guard let data = data else {
                print(error?.localizedDescription ?? "Unknown error")
                return
            }

            let decoder = JSONDecoder()

            if let people = try? decoder.decode([Users].self, from: data) {
                DispatchQueue.main.async {
                    self.users = people
                    print("Loaded \(people.count) users.")
                    print(people[0].login)
                    print(people[1].login)

                }
            } else {
                print("Unable to parse JSON response.")
            }

        }.resume()


    }

  }
oodle
  • 1
  • 1
  • 1
    The call to `dataTask` only configures the completion handler runs, and returns immediately. The completion handler runs ... upon completion. See https://stackoverflow.com/q/38256047/3141234 – Alexander Feb 15 '20 at 18:13
  • Not sure why you are populating users using DispatchQueue, perhaps this is part of the issue? – Alec. Feb 15 '20 at 18:17

0 Answers0