Lê Khánh Vinh Lê Khánh Vinh - 1 year ago 458
iOS Question

IOS Swift 3 create URLSession extension for synchronous and asynchronous request

Hi every one I'm about to create an extension for

in swift 3 to create synchronous and asynchronous request. Here is my implementation

extension URLSession {
func sendSynchronousRequest(request: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) {
let semaphore = DispatchSemaphore(value: 0)

let task = self.dataTask(with: request) { (data, response, error) in
semaphore.wait(timeout: .distantFuture)

func sendAsynchronousRequest(request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask {
let task = self.dataTask(with: request) { data, response, error in
completionHandler(data, response, error)
return task

I have Xcode suggest me to insert the @escaping to the function. Don't know whether the implementation is correct

i also have warning at this line enter image description here

Anyone know how to correct the extension? Help is much appreciate! thanks!

Answer Source

I found this implementation but in swift1/2 can't remember. This is not my own. But i rewrote it in swift3. I just can't remember where i found it :/

func synchronousDataTaskWithURL(url: URL) -> (Data?, URLResponse?, Error?) {
    var data: Data?, response: URLResponse?, error: Error?

    let semaphore = DispatchSemaphore(value: 0)

    dataTask(with: url) {
        data = $0; response = $1; error = $2


    return (data, response, error)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download