How to cancel a download request when cancel button pressed in swift

旧城冷巷雨未停 提交于 2019-12-21 23:04:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!