我对默认情况下在后台线程上运行Alamofire的做法有误。默认情况下,它实际上在主队列上运行。我已经在Alamofire的Github页面上打开了一个问题,并在这里解决了:https
:
//github.com/Alamofire/Alamofire/issues/1922
解决我的问题的正确方法是使用.responseJSON方法中的“ queue ”参数指定我希望在哪种队列上运行我的请求(
.responseJSON(queue: queue) { response in...})
这是我的代码的完整更正版本:
let productsEndPoint: String = "http://api.test.com/Products?username=testuser" let queue = DispatchQueue(label: "com.test.api", qos: .background, attributes: .concurrent) Alamofire.request(productsEndPoint, method: .get) .responseJSON(queue: queue) { response in // check for errors guard response.result.error == nil else { // got an error in getting the data, need to handle it print("Inside error guard") print(response.result.error!) return } // make sure we got some JSON since that's what we expect guard let json = response.result.value as? [String: Any] else { print("didn't get products as JSON from API") print("Error: (response.result.error)") return } // get and print the title guard let products = json["products"] as? [[String: Any]] else { print("Could not get products from JSON") return } print(products) }


