2014-10-10 65 views
18

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

回答

29

保持在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() 
} 
+0

這是否取消所有請求? – 2015-07-16 09:54:30

+2

'request.cancel()'不保證立即取消請求。這使取消後調用進度塊。有沒有任何內置的方法來檢查取消/掛起是否被調用? – osrl 2016-04-27 10:35:52

+0

暫停是請求?.suspend()或請求?取消()? – Steve 2016-06-27 06:47:00

16

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

暫停和取消有什麼區別?暫停更類似於暫停? – 2017-08-11 03:19:38