I have this code from here to do synchronous request of a URL on Swift 2.
func send(url: String, f: (String)-> ()) {
var request = NSURLRequest(URL:
Based on @fpg1503 answer I made a simple extension in Swift 3:
extension URLSession {
func synchronousDataTask(with request: URLRequest) throws -> (data: Data?, response: HTTPURLResponse?) {
let semaphore = DispatchSemaphore(value: 0)
var responseData: Data?
var theResponse: URLResponse?
var theError: Error?
dataTask(with: request) { (data, response, error) -> Void in
responseData = data
theResponse = response
theError = error
semaphore.signal()
}.resume()
_ = semaphore.wait(timeout: .distantFuture)
if let error = theError {
throw error
}
return (data: responseData, response: theResponse as! HTTPURLResponse?)
}
}
Then you simply call:
let (data, response) = try URLSession.shared.synchronousDataTask(with: request)