Skip to content

Instantly share code, notes, and snippets.

@adagio
Created November 15, 2018 17:13
Show Gist options
  • Save adagio/9a3febfdac29f2b2fad55cf60bd54cb6 to your computer and use it in GitHub Desktop.
Save adagio/9a3febfdac29f2b2fad55cf60bd54cb6 to your computer and use it in GitHub Desktop.
HTTP request with URLSession
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let url = URL(string: "https://httpbin.org/anything")!
let task = session.dataTask(with: url) { data, response, error in
// ensure there is no error for this HTTP response
guard error == nil else {
print ("error: \(error!)")
return
}
// ensure there is data returned from this HTTP response
guard let content = data else {
print("No data")
return
}
// serialise the data / NSData object into Dictionary [String : Any]
guard let json = (try? JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [String: Any] else {
print("Not containing JSON")
return
}
print("gotten json response dictionary is \n \(json)")
// update UI using the response here
}
// execute the HTTP request
task.resume()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment