0

I have this code which- as far as I understand- is async:

func testConnection() -> Bool {
    let url = URL(string: uri)!
    let task = URLSession.shared.dataTask(with: url) {
        (data, response, error) in

        guard let data = data, let _:URLResponse = response , error == nil else {
            print("error")
            return
        }

        let dataString =  String(data: data, encoding: String.Encoding.utf8)
    }

    task.resume()
}

How would a synchronous version look that allows to return the testConnection result to the sender?

andig
  • 13,378
  • 13
  • 61
  • 98
  • Possible duplicate of [Returning data from async call in Swift function](http://stackoverflow.com/questions/25203556/returning-data-from-async-call-in-swift-function) – vadian Oct 11 '16 at 20:37
  • 1
    I know that you want the sync version but why? try to not complicate too much and instead start thinking async with network requests. – Wilson Oct 15 '16 at 12:33

1 Answers1

-2

You could use a semaphore to wait for the async call to finish:

func testConnection() -> Bool {
    let url = URL(string: uri)!
    var dataStringOrNil: String?
    let semaphore = DispatchSemaphore(value: 0)

    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        defer {
            semaphore.signal()
        }

        guard let data = data, error == nil else {
            print("error")
            return
        }

        dataStringOrNil = String(data: data, encoding: .utf8)
    }

    task.resume()
    semaphore.wait()

    guard let dataString = dataStringOrNil else {
        return false
    }

    // some substring checking
    return dataString.contains("href")
}

I wouldn't recommend it, but there can be reasons for sync calls. We use them sometimes in command-line tools.