Created
February 15, 2018 22:29
-
-
Save groz/85b95f663f79ba17946269ea65c2c0f4 to your computer and use it in GitHub Desktop.
Synchronous http request in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)") |
NSLock is better because we have only one thread.
Can only be better if it actually worked.
Original works, NSLock version exits straightaway as pointed out by @eonil
The NSLock class uses POSIX threads to implement its locking behavior. When sending an unlock message to an NSLock object, you must be sure that message is sent from the same thread that sent the initial lock message. Unlocking a lock from a different thread can result in undefined behavior. https://developer.apple.com/documentation/foundation/nslock
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@impul Are you sure that code work? It seems
query
function exits beforeresult
getting set.