我正在尝试发出一个URL请求,但是在让另一个URL请求通过使用信号量之前等待它完成。似乎以下代码等待信号量超时(10秒),然后才发生数据任务响应。
换句话说,在超时发生之前,执行不会转到semaphore.signal()。如果我将超时设置为“distantFuture”,则执行会挂起。
static func makeHTTPPostRequestJsonWait(path: String, body: [String: AnyObject], onCompletion: @escaping ServiceResponse) {
var request = URLRequest(url: URL(string: path)!)
let semaphore = DispatchSemaphore(value: 0)
// Set the method to POST
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let json = JSON(body)
let jsonString = json.rawString()
// Set the POST body for the request
let jsonBody = jsonString?.data(using: String.Encoding.utf8)
request.httpBody = jsonBody
let session = URLSession.shared
let task = session.dataTask(with: request) { data, response, error in
semaphore.signal()
if let jsonData = data {
let json:JSON = JSON(data: jsonData)
onCompletion(json, nil)
} else {
onCompletion(nil, error)
}
}
task.resume()
_ = semaphore.wait(timeout: DispatchTime.now() + 10)
}