使用信号量的数据任务不按预期工作

时间:2017-04-12 06:59:10

标签: ios swift swift3

我正在尝试发出一个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)
}

0 个答案:

没有答案