将Alamofire请求转换为同步?
问题描述:
如何将当前的Alamofire请求转换为同步请求?这会停止所有其他执行,直到请求完成为止吗?将Alamofire请求转换为同步?
我目前的功能如下:
func updateLabels() {
Alamofire.request(apiUrl).responseJSON { response in
if let data = response.result.value {
var rawJson = JSON(data)
var json = rawJson[0]
var totalViews = json["totalViews"].stringValue
var uniqueUsers = json["uniqueUsers"].stringValue
print(totalViews)
print(uniqueUsers)
self.totalViews.setText(totalViews)
self.uniqueUsers.setText(uniqueUsers)
}
}
}
我使用Alamofire_Synchronous
。我对Alamofire不是很熟悉,所以任何帮助都会很棒,谢谢!
答
您可以使用此扩展名并呼叫同步请求到Alamofire
库。
extension Alamofire.Manager {
func syncRequest(URLRequest: URLRequestConvertible) -> Response<AnyObject, NSError> {
var outResponse: Response<AnyObject, NSError>!
let semaphore: dispatch_semaphore_t! = dispatch_semaphore_create(0)
self.request(URLRequest).responseJSON { (response: Response<AnyObject, NSError>) -> Void in
outResponse = response
dispatch_semaphore_signal(semaphore)
}
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
return outResponse
}
}
我认为,这种联系将帮助你 https://stackoverflow.com/questions/39961010/how-to-make-a-synchronous-request-using-alamofire –