Skip to content

Instantly share code, notes, and snippets.

@quangtqag
Created March 5, 2020 10:04
Show Gist options
  • Save quangtqag/cdd51ab9f34ed6380bbabb218c3338e2 to your computer and use it in GitHub Desktop.
Save quangtqag/cdd51ab9f34ed6380bbabb218c3338e2 to your computer and use it in GitHub Desktop.
static func getUsers(completionHandler: @escaping (_ users: [User]?, _ error: Error?) -> Void) {
let endpointUrl = URL(string: host + listUsersPath)!
let urlRequest = URLRequest(url: endpointUrl)
let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
guard error == nil else {
print("error calling GET on \(listUsersPath): \(error!)")
DispatchQueue.main.async {
completionHandler(nil, error)
}
return
}
let usersData = try! JSONSerialization.jsonObject(with: data!, options: []) as! [Any]
var users = [User]()
for userData in usersData {
let userDict = userData as! Dictionary<String, Any>
let name = userDict["name"] as! String
let id = userDict["id"] as! Double
let user = User(id: id, name: name)
users.append(user)
}
DispatchQueue.main.async {
completionHandler(users, nil)
}
}
task.resume()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment