IOS Swift 3 create URLSession extension for synchronous and asynchronous request -
hi every 1 i'm create extension urlsession
in swift 3 create synchronous , asynchronous request. here 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 insert @escaping function. don't know whether implementation correct
anyone know how correct extension? appreciate! thanks!
i found implementation in swift1/2 can't remember. not own. rewrote in swift3. can't remember found :/
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) }
Comments
Post a Comment