Skip to content

Instantly share code, notes, and snippets.

@groz
Created February 15, 2018 22:29
Show Gist options
  • Select an option

  • Save groz/85b95f663f79ba17946269ea65c2c0f4 to your computer and use it in GitHub Desktop.

Select an option

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

impul commented Sep 26, 2019

Copy link
Copy Markdown

NSLock will be better here

@rkxx08

rkxx08 commented Oct 15, 2019

Copy link
Copy Markdown

NSLock will be better here

How? @impul

@impul

impul commented Oct 16, 2019

Copy link
Copy Markdown

@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)")

@rkxx08

rkxx08 commented Oct 16, 2019

Copy link
Copy Markdown

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

@mehdico

mehdico commented Jun 25, 2020

Copy link
Copy Markdown

NSLock is better because we have only one thread.

@brett-eugenelabs

Copy link
Copy Markdown

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

@ppave

ppave commented Nov 13, 2020

Copy link
Copy Markdown

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