【问题标题】:Convert Alamofire request to synchronous?将 Alamofire 请求转换为同步?
【发布时间】:2017-06-05 03:32:16
【问题描述】:

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

【问题讨论】:

标签: swift swift3 alamofire synchronous swifty-json


【解决方案1】:

您可以使用此扩展程序并向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
    }
}

【讨论】:

  • 您好,希望您一切顺利。我可以问一个与同步有关的问题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-19
  • 2013-03-09
  • 2019-09-21
  • 1970-01-01
  • 2018-05-22
  • 1970-01-01
  • 2017-06-10
相关资源
最近更新 更多