Home > Uncategorized > Make a #Synchronous #HTTP request in #Swift3

Make a #Synchronous #HTTP request in #Swift3

swift

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 = $2

semaphore.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”)
}

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: