Last active
October 15, 2019 10:44
-
-
Save eonil/00e0e4d09deb8ab9861d22d6013cba6c to your computer and use it in GitHub Desktop.
The most reliable and quick way to perform synchronous HTTP call with URLSession. See https://github.com/eonil/swift-sync-http for packaged library.
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
enum HTTP { | |
/// - Note: | |
/// This does not consider HTTP status into success/failure. | |
/// Returning result can be non 2xx status. | |
static func get(address:String, query: [URLQueryItem] = []) throws -> Data { | |
let u = URL(string: address)! | |
var reply = Data() | |
/// We need to make a session object. | |
/// This is key to make this work. This won't work with shared session. | |
let conf = URLSessionConfiguration.ephemeral | |
let sess = URLSession(configuration: conf) | |
let task = sess.dataTask(with: u) { data, _, _ in | |
reply = data ?? Data() | |
} | |
task.resume() | |
while task.state != .completed { | |
Thread.sleep(forTimeInterval: 0.1) | |
} | |
FileHandle.standardOutput.write(reply) | |
if let err = task.error { | |
throw err | |
} | |
guard let res = task.response else { return Data() } | |
print(res) | |
return reply | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment