Warning:\'sendSynchronousRequest(_:returningResponse:)\' was deprecated in iOS 9.0: Use [NSURLSession dataTaskWithRequest:completionHandler:] (see NSURLSe
Swift 4 / Xcode 9
If you really want the request to be synchronous like in the deprecated semantics, you can block the main thread with an empty loop on a condition set true by the completion handler:
let request = URLRequest(url: URL(string: "YOUR_URL")!)
let session = URLSession.shared
var gotResp = false
let task = session.dataTask(with: request,
completionHandler: { data, response, error -> Void in
// do my thing...
gotResp = true
})
task.resume()
// block thread until completion handler is called
while !gotResp {
// wait
}
print("Got response in main thread")
...
EDIT: or if you prefer to use semaphores like in the Obj-C Nick H247 answer:
let request = URLRequest(url: URL(string: "YOUR_URL")!)
let session = URLSession.shared
let ds = DispatchSemaphore( value: 0 )
let task = session.dataTask(with: request,
completionHandler: { data, response, error -> Void in
// do my thing..., then unblock main thread
ds.signal()
})
task.resume()
// block thread until semaphore is signaled
ds.wait()
print("Got response in main thread")
...