Skip to content

Instantly share code, notes, and snippets.

@AppleCEO
Forked from groz/sync-http.swift
Created September 1, 2019 14:38
Show Gist options
  • Save AppleCEO/67d7f869d7f2fd14c3b20e36b0db9d4d to your computer and use it in GitHub Desktop.
Save AppleCEO/67d7f869d7f2fd14c3b20e36b0db9d4d to your computer and use it in GitHub Desktop.
Synchronous http request in Swift
import Foundation
func query(address: String) -> String {
let url = URL(string: address)
let semaphore = DispatchSemaphore(value: 0)
var result: String = ""
let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
result = String(data: data!, encoding: String.Encoding.utf8)!
semaphore.signal()
}
task.resume()
semaphore.wait()
return result
}
let preference = query(address: "http://the-rock-paper-scissors.herokuapp.com/newgame")
print("Computer preference: \(preference)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment