Created
March 5, 2020 10:04
-
-
Save quangtqag/cdd51ab9f34ed6380bbabb218c3338e2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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