Make a #Synchronous #HTTP request in #Swift3
Often you may want to chain HTTP requests in Swift, So, you may want to request something, then wait until that’s finished before doing something else. – for example, you may not want your terminal script to exit before the last HTTP call is made. So cobbling together a few code examples, this is what I came up with
import Foundation
extension URLSession {
func synchronousDataTask(urlrequest: URLRequest) -> (Data?, URLResponse?, Error?) {
var data: Data?
var response: URLResponse?
var error: Error?let semaphore = DispatchSemaphore(value: 0)
let dataTask = self.dataTask(with: urlrequest) {
data = $0
response = $1
error = $2semaphore.signal()
}
dataTask.resume()_ = semaphore.wait(timeout: .distantFuture)
return (data, response, error)
}
}var request = URLRequest(url: URL(string: “http://icanhazip.com”)!)
request.httpMethod = “GET”
let (data, response, error) = URLSession.shared.synchronousDataTask(urlrequest: request)
if let error = error {
print(“Synchronous task ended with error: \(error)”)
}
else {
print(NSString(data: data!, encoding: String.Encoding.utf8.rawValue) ?? “Error”)
}