如何在Alamofire中暂停/恢复/取消我的下载请求

时间:2014-10-10 18:22:24

标签: ios swift alamofire

我正在使用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
}

2 个答案:

答案 0 :(得分:34)

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

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

答案 1 :(得分:20)

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