如何在 swift 中按下取消按钮时取消下载请求
How to cancel a download request when cancel button pressed in swift
我想在按下取消按钮时取消下载请求。
现在,当我按下下载按钮时,代码有效
@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)
}
}
我的下载器class是
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()
}
}
那么如何在按下取消按钮时取消请求
您的 load()
函数需要 return
您创建的 NSURLSessionDataTask
。然后您调用 task.cancel()
取消请求
我想在按下取消按钮时取消下载请求。 现在,当我按下下载按钮时,代码有效
@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)
}
}
我的下载器class是
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()
}
}
那么如何在按下取消按钮时取消请求
您的 load()
函数需要 return
您创建的 NSURLSessionDataTask
。然后您调用 task.cancel()
取消请求