Skip to content

Instantly share code, notes, and snippets.

@fredlahde
Last active March 16, 2017 21:37
Show Gist options
  • Save fredlahde/c914131bac2c2a2eacfef60d97027d59 to your computer and use it in GitHub Desktop.
Save fredlahde/c914131bac2c2a2eacfef60d97027d59 to your computer and use it in GitHub Desktop.
Basic async http get in swift with closure
import PlaygroundSupport
import Foundation
func get(with: String ,callback: @escaping (_ data : [String : Any], _ succes : Bool) -> Void) -> Void {
let url = URL(string: with)
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
guard error == nil else {
print(error!)
return
}
guard let data = data else {
print("Data is empty")
return
}
if let httpResponse = response as? HTTPURLResponse {
let succes = httpResponse.statusCode == 200
let json = try! JSONSerialization.jsonObject(with: data, options: []) as! [String:Any]
callback(json, succes)
}
}
task.resume();
}
get(with: "https://httpbin.org/ip", callback: {data, succes in
if (succes) {
let ip = data["origin"]
print(ip!)
return
}
print("error")
})
// Only neede in Playground
// PlaygroundPage.current.needsIndefiniteExecution = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment