简体   繁体   中英

Cancel NSURLSession if user taps twice in swift iOS

Im using NSURLSession which is preferred according to this thread. How to make an HTTP request in Swift?

let url = NSURL(string: "http://www.stackoverflow.com")

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
    println(NSString(data: data, encoding: NSUTF8StringEncoding))
}

task.resume()

My only problem is when user taps twice and I want to cancel the first request. I have tried task.cancel() but the print statement is still executed (namely right after .cancel() with NSDomainError). How do I safely cancel this request (NSURLSessionDataTask), without firing the print statement, or is it even possible?

EDIT: Just to be clear. The URL could be the same and I want to cancel the first request.

This is how I solved the problem. When task.cancel() is performed, the print statement wont be executed. Seems a little hacky to check against a string so if anyone has a better solution I will accept that one.

let url = NSURL(string: "http://www.stackoverflow.com")

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
    if (error?.userInfo?["NSLocalizedDescription"] as? String) == "cancelled"
            {
                return
            }
    println(NSString(data: data, encoding: NSUTF8StringEncoding))
}

task.resume()

I hope this is something you can use:

class ViewController: UIViewController , NSURLSessionDownloadDelegate {

    var download : NSURLSessionDownloadTask?
    var backgroundSession : NSURLSession?

    override func viewDidLoad() {
        super.viewDidLoad()

        let sessionConfiguration : NSURLSessionConfiguration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("CustomBackgroundIdentifier")
        backgroundSession = NSURLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: NSOperationQueue.mainQueue())

        var btn = UIButton(frame: CGRectMake(0, 0, 100, 100))
        btn.backgroundColor = UIColor.redColor()
        btn.addTarget(self, action: "startDownload", forControlEvents: UIControlEvents.TouchDown)
        self.view.addSubview(btn)

        var btn2 = UIButton(frame: CGRectMake(0, 120, 100, 100))
        btn2.backgroundColor = UIColor.blueColor()
        btn2.addTarget(self, action: "cancelDownload", forControlEvents: UIControlEvents.TouchDown)
        self.view.addSubview(btn2)

    }

    func startDownload() {
        if download == nil {
            if let url = NSURL(string: "http://www.stackoverflow.com") {
                download = backgroundSession?.downloadTaskWithURL(url)
                download?.resume()
            }
        } else {
            resumeDownload()
        }
    }

    func pauseDownload() {
        if download != nil {
            download?.suspend()
        }
    }

    func resumeDownload() {
        if download != nil {
            download?.resume()
        }
    }

    func cancelDownload() {
        if download != nil {
            download?.cancel()
        }
    }

    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
        println("Session %@ download task %@ finished downloading to URL %@\n",
        session, downloadTask, location)
    }

    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
        println("downloaded: %i",totalBytesWritten)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM