Lê Khánh Vinh Lê Khánh Vinh - 20 days ago 22
iOS Question

IOS Swift 3 create URLSession extension for synchronous and asynchronous request

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

URLSession
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
completionHandler(data,response,error)
semaphore.signal()
}
task.resume()
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)
}
task.resume()
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

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
        semaphore.signal()
        }.resume()

    semaphore.wait()

    return (data, response, error)
}