Skip to content

Instantly share code, notes, and snippets.

@groz
Created February 15, 2018 22:29
Show Gist options
  • Star 30 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save groz/85b95f663f79ba17946269ea65c2c0f4 to your computer and use it in GitHub Desktop.
Save groz/85b95f663f79ba17946269ea65c2c0f4 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)")
@impul
Copy link

impul commented Sep 26, 2019

NSLock will be better here

@eonil
Copy link

eonil commented Oct 15, 2019

NSLock will be better here

How? @impul

@impul
Copy link

impul commented Oct 16, 2019

@eonil ,

import Foundation

func query(address: String) -> String {
    let url = URL(string: address)
    let lock = NSLock()
    
    var result: String = ""
    
    let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
        result = String(data: data!, encoding: String.Encoding.utf8)!
        lock.unlock()
    }
    
    task.resume()
    lock.lock()
    return result
}

let preference = query(address: "http://the-rock-paper-scissors.herokuapp.com/newgame")
print("Computer preference: \(preference)")

@eonil
Copy link

eonil commented Oct 16, 2019

@impul Are you sure that code work? It seems query function exits before result getting set.

@mehdico
Copy link

mehdico commented Jun 25, 2020

NSLock is better because we have only one thread.

@brett-eugenelabs
Copy link

Can only be better if it actually worked.
Original works, NSLock version exits straightaway as pointed out by @eonil

@ppave
Copy link

ppave commented Nov 13, 2020

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