swift - Swift 上使用完成处理程序和 DispatchSemaphore 的异步请求
问题描述
我正在尝试使用andasync
对 Swift 提出请求。我需要得到响应,然后将其返回给另一个方法,所以基本上这是我的代码Alamofire's
completion handler
DispatchSemaphores
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
返回“真”/“假”
解决方案
您的 return 语句在完成处理程序之外,因此它将立即运行,返回它的初始 false 值,而不是按照您的要求返回请求的结果。
您应该删除响应属性并在完成处理程序中处理响应。
推荐阅读
- c# - 如何在 Web API 操作中指定动态值类型参数?
- php - HEREDOC 文本和变量格式问题
- angular - 如何在 catchError 代码块中使用代码
- javascript - Redux 商店未连接
- javascript - 如何在画布上为带有背景图像的球设置动画?
- javascript - 当 toString 或 valueOf 都不返回堆栈时,console.log 如何获取错误堆栈?
- javascript - JS/CSS:动画一个从另一个圆圈向外扩展的圆圈
- java - Java 中的套接字发送数据流失败
- database - Mongo-Go-Driver 连接失败
- sql - SQL 查找列中每个“动态”类型的总数