Last active
March 16, 2017 21:37
-
-
Save fredlahde/c914131bac2c2a2eacfef60d97027d59 to your computer and use it in GitHub Desktop.
Basic async http get in swift with closure
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
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