title: How to make synchronous url requests with swift 3
body: <p>I know the question has been asked before and I agree with most answers that claim it is better to follow the way requests are made async with URLSession in Swift 3. I haver the following scenario, where async request cannot be used.</p>
  
  <p>With Swift 3 and the ability to run swift on servers I have the following problem.</p>
  
  <ol>
  <li>Server Receives a request from a client</li>
  <li>To process the request the server has to send a url request and wait for the response to arrive.</li>
  <li>Once response arrives, process it and reply to the client</li>
  </ol>
  
  <p>The problem arrises in step 2, where URLSession gives us the ability to initiate an async data task only. Most (if not all) server side swift web frameworks do not support async responses. When a request arrives to the server everything has to be done in a synchronous matter and at the end send the response.</p>
  
  <p>The only solution I have found so far is using DispatchSemaphore (see example at the end) and I am not sure whether that will work in a scaled environment.</p>
  
  <p>Any help or thoughts would be appreciated.</p>
  
  <pre><code>extension URLSession {
      func synchronousDataTaskWithURL(_ url: URL) -&gt; (Data?, URLResponse?, Error?) {
          var data: Data?
          var response: URLResponse?
          var error: Error?
  
          let sem = DispatchSemaphore(value: 0)
  
          let task = self.dataTask(with: url as URL, completionHandler: {
              data = $0
              response = $1
              error = $2 as Error?
              sem.signal()
          })
  
          task.resume()
  
          let result = sem.wait(timeout: DispatchTime.distantFuture)
          switch result {
          case .success:
              return (data, response, error)
          case .timedOut:
              let error = URLSessionError(kind: URLSessionError.ErrorKind.timeout)
              return (data, response, error)
  
          }
      }
  }
  </code></pre>
  
  <p>I only have experience with kitura web framework and this is where i faced the problem. I suppose that similar problems exist in all other swift web frameworks.</p>