问题
I want to cancel the download request when i press the cancel button. Now when i press download button following code works
@IBAction func downloadButtonPressed(sender: UIButton) {
var fileName = noticeAttacchment[0]["fileName"] as! String
var fileUrl = noticeAttacchment[0]["fileUrl"] as! String
if var URL = NSURL(string: fileUrl){
Api.load(URL, fileName: fileName)
}
}
And my downloader class is
class Api {
class func load(URL: NSURL , fileName : String) {
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = "GET"
let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if (error == nil) {
FileSave.saveData(
data, directory: NSSearchPathDirectory.CachesDirectory, path: fileName, subdirectory: "edstem")
}
else {
println("Faulure: %@", error.localizedDescription);
}
})
task.resume()
}
}
So how to cancel the request when cancel button pressed
回答1:
Your load()
function needs to return
the NSURLSessionDataTask
you created. You then call task.cancel()
to cancel the request
additional Reference
来源:https://stackoverflow.com/questions/32002133/how-to-cancel-a-download-request-when-cancel-button-pressed-in-swift