21

I am downloading a file using Alamofire download with progress but i have no idea how to pause / resume / cancel the specific request.

@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
}
Victor Sigler
  • 23,243
  • 14
  • 88
  • 105
Zeeshan
  • 211
  • 1
  • 2
  • 3

2 Answers2

36

Keep a reference to the request created in downloadBtnTapped with a property, and call cancel on that property in 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()
}
mattt
  • 19,544
  • 7
  • 73
  • 84
  • Does this cancel all request? – Alex Lacayo Jul 16 '15 at 09:54
  • 2
    `request.cancel()` doesn't guarantee to cancel the request immediately. This makes progress block to be called after the cancel. Is there any built-in way to check if the cancel/suspend is called? – osrl Apr 27 '16 at 10:35
  • Pausing is request?.suspend() OR request?. cancel() ? – Stephen Jun 27 '16 at 06:47
  • From offical docs: **`suspend()`: Suspends the underlying task and dispatch queue. `resume()`: Resumes the underlying task and dispatch queue. If the owning manager does not have.** So suspend pauses a request. – aytek Jul 01 '16 at 15:23
24

request.cancel() will cancel the download progress. If you want to pause and continue, you can use:

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()
}
marmaralone
  • 516
  • 6
  • 11