将Alamofire请求转换为同步?

时间:2017-06-05 03:32:17

标签: swift swift3 alamofire synchronous swifty-json

如何将当前的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并不是很熟悉,所以任何帮助都会很棒,谢谢!

1 个答案:

答案 0 :(得分:3)

您可以使用此扩展名并向Alamofire lib调用同步请求。

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
    }
}