Skip to content

Instantly share code, notes, and snippets.

@eonil
Last active October 15, 2019 10:44
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 eonil/00e0e4d09deb8ab9861d22d6013cba6c to your computer and use it in GitHub Desktop.
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.
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