首页 > 解决方案 > Swift 上使用完成处理程序和 DispatchSemaphore 的异步请求

问题描述

我正在尝试使用andasync对 Swift 提出请求。我需要得到响应,然后将其返回给另一个方法,所以基本上这是我的代码Alamofire's completion handlerDispatchSemaphores

func customRequest(zipCode: String) -> Bool{
    var response = false

    let dispatchQueueProcess = DispatchQueue.global(qos: .userInitiated)
    let semaphore = DispatchSemaphore(value: 1)
    
    dispatchQueueProcess.async {
        
        semaphore.wait()

        apiRequest(zipCode: zipCode) { apiResponse in
        
            if apiResponse != nil {
            
response = apiResponse
               
             
            } else {
                print("Server did not Response")
            }
            
            semaphore.signal()
            
            
        }
    }
    
    return response
}

问题是请求总是返回false,因为没有等到apiRequest响应......你有什么想法来解决这个问题吗?太感谢了!

附言。apiRequest返回“真”/“假”

标签: swiftsignalsdispatchsemaphore

解决方案


您的 return 语句在完成处理程序之外,因此它将立即运行,返回它的初始 false 值,而不是按照您的要求返回请求的结果。

您应该删除响应属性并在完成处理程序中处理响应。


推荐阅读