【问题标题】:How to pause/resume/cancel my download request in Alamofire如何在 Alamofire 中暂停/恢复/取消我的下载请求
【发布时间】:2014-12-05 23:51:54
【问题描述】:

我正在使用 Alamofire 下载一个有进度的文件,但我不知道如何暂停/恢复/取消特定请求。

@IBAction func downloadBtnTapped() {

 Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination)
     .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in
         println(totalBytesRead)
     }
     .response { (request, response, _, error) in
         println(response)
     }
}


@IBAction func pauseBtnTapped(sender : UIButton) {        
    // i would like to pause/cancel my download request here
}

【问题讨论】:

    标签: ios swift alamofire


    【解决方案1】:

    request.cancel() 将取消下载进度。如果要暂停并继续,可以使用:

    var request: Alamofire.Request?
    
    @IBAction func downloadBtnTapped() {
     self.request = Alamofire.download(.GET, "http://yourdownloadlink.com", destination: destination)
    }
    
    @IBAction func pauseBtnTapped(sender : UIButton) {
      self.request?.suspend()
    }
    
    @IBAction func continueBtnTapped(sender : UIButton) {
      self.request?.resume()
    }
    
    @IBAction func cancelBtnTapped(sender : UIButton) {
      self.request?.cancel()
    }
    

    【讨论】:

    • 挂起和取消有什么区别?暂停和暂停更相似吗?
    【解决方案2】:

    使用属性保留对在downloadBtnTapped 中创建的请求的引用,并在pauseBtnTapped 中对该属性调用cancel

    var request: Alamofire.Request?
    
    @IBAction func downloadBtnTapped() {
     self.request = Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination)
    }
    
    @IBAction func pauseBtnTapped(sender : UIButton) {
      self.request?.cancel()
    }
    

    【讨论】:

    • 这会取消所有请求吗?
    • request.cancel() 不保证立即取消请求。这使得在取消后调用进度块。是否有任何内置方法可以检查是否调用了取消/暂停?
    • 暂停是 request?.suspend() OR request?。取消()?
    • 来自官方文档:suspend():暂停底层任务和调度队列。 resume():恢复底层任务和调度队列。如果拥有的经理没有。所以suspend暂停一个请求。
    猜你喜欢
    • 2021-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 1970-01-01
    • 2012-08-27
    相关资源
    最近更新 更多