0

Using the software Postman to test a webserver for REST. It can generate swift code as an output. The following examples does work in Xcode 11+

import Foundation

var semaphore = DispatchSemaphore (value: 0)

var request = URLRequest(url: URL(string: "http://www.somewhere.com/image.png")!,timeoutInterval: 1000)
request.httpMethod = "GET"

let task = URLSession.shared.dataTask(with: request) { data, response, error in 
  guard let data = data else {
    print(String(describing: error))
    return
  }
  print(String(data: data, encoding: .utf8)!)
  semaphore.signal()
}

task.resume()
semaphore.wait()

Usual code looks like this

let url = URL(string: "https://www.example.com/")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
    if let error = error {
        self.handleClientError(error)
        return
    }
    guard let httpResponse = response as? HTTPURLResponse,
        (200...299).contains(httpResponse.statusCode) else {
        self.handleServerError(response)
        return
    }
    if let mimeType = httpResponse.mimeType, mimeType == "text/html",
        let data = data,
        let string = String(data: data, encoding: .utf8) {
        DispatchQueue.main.async {
            self.webView.loadHTMLString(string, baseURL: url)
        }
    }
}
task.resume()

Is the semaphore needed for this case?

Skynet
  • 25
  • 1
  • 5
  • 1
    No, you should not use a semaphore for such a simple async task. As explained in the linked duplicate, you should use a completion handler to return data from an async function, such as `URLSession.dataTask`. – Dávid Pásztor Jul 15 '20 at 12:12
  • 1
    Well, it’s okay for them to do in a test. But you should not use semaphore in your code. Real code should never wait, and XCTest code should use XCTExpectation. – matt Jul 15 '20 at 12:14

0 Answers0