延迟Alamofire请求

时间:2017-05-24 14:17:42

标签: ios swift alamofire

我们正在使用Alamofire进行API调用,并希望它是异步但延迟2秒。我们正在使用它来延迟调用,但我认为这可能导致在主线程上运行某些东西。等待2秒钟运行这样的请求的最佳方法是什么?

DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
     //This is the Alamofire API call
     self.excecuteGetRequest(id, product: product)
}

这是我尝试的其他东西,但我不确定它是否正确。

DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {

     let qualityOfServiceClass = DispatchQoS.QoSClass.userInitiated
     let backgroundQueue = DispatchQueue.global(qos: qualityOfServiceClass)
     backgroundQueue.async(execute: {
          self.excecuteGetRequest(cartID, product: product)
     })
}

如果有帮助,这是请求:

func excecuteGetRequest(_ id:String,product:Product) {
    let url = "www.api.sampleAPI.com/random"

    Alamofire.request(url).responseJSON(completionHandler: { (innerResponse) in
        print("Inner response = \(innerResponse)")
    }
}

1 个答案:

答案 0 :(得分:2)

你可以做这样的事情

let requestQueue = DispatchQueue(label: "alamofire.queue")
requestQueue.asyncAfter(deadline: DispatchTime.now() + 2.0) {
    //Do your Alamofire request here
    //After it complete his task return response in main queue if needed
    DispatchQueue.main.async {
        //you can return response like this
    }
}