Skip to content

Instantly share code, notes, and snippets.

@quangtqag
Created March 5, 2020 10:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quangtqag/5e4dbdd95043a305420214b5d12e8fbf to your computer and use it in GitHub Desktop.
Save quangtqag/5e4dbdd95043a305420214b5d12e8fbf to your computer and use it in GitHub Desktop.
static func addUser(name: String, completionHandler: @escaping (_ userID: Double?, _ error: Error?) -> Void) {
let endpointUrl = URL(string: host + addUserPath)!
var urlRequest = URLRequest(url: endpointUrl)
urlRequest.httpMethod = "POST"
let newUser: [String: Any] = ["name": name]
let jsonUser = try! JSONSerialization.data(withJSONObject: newUser, options: [])
urlRequest.httpBody = jsonUser
let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
guard error == nil else {
print("error calling POST on \(addUserPath): \(error!)")
DispatchQueue.main.async {
completionHandler(nil, error)
}
return
}
let userData = try! JSONSerialization.jsonObject(with: data!, options: []) as! [String: Double]
let userID = userData["id"]
DispatchQueue.main.async {
completionHandler(userID, nil)
}
}
task.resume()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment