等待异步完成DispatchSemaphore

时间:2017-05-09 13:11:18

标签: swift alamofire

从下面的代码中,我希望打印" 1"而不是" 0"用alamofire实现信号量。你知道为什么吗?

public func mySync() -> NSNumber{

    let headers: HTTPHeaders = ["":""]
    let parameters: Parameters = ["":""]

    let semaphore = DispatchSemaphore(value: 1)

    var aNumber: NSNumber = 0

    Alamofire.request(
        "http://localhost:8000/users.json",
        method: .post,
        parameters: parameters,
        encoding: URLEncoding.default,
        headers: headers).responseJSON { (response) in
            aNumber = 1
            semaphore.signal()
    }

    _ = semaphore.wait(timeout: DispatchTime.distantFuture)
    return aNumber
}

print(mySync())

PlaygroundPage.current.needsIndefiniteExecution = true

0 个答案:

没有答案