如果用户在swift iOS中点击两次,则取消NSURLSession

时间:2015-06-16 12:25:28

标签: ios swift nsurlsession

我使用NSURLSession,这是根据这个线程首选。 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()

我唯一的问题是当用户点击两次并且我想取消第一个请求时。我已经尝试过task.cancel()但是仍然执行了print语句(即在带有NSDomainError的.cancel()之后)。如何安全地取消此请求(NSURLSessionDataTask),而不触发print语句,或者甚至是否可能?

编辑: 只是为了清楚。 URL可以是相同的,我想取消第一个请求。

2 个答案:

答案 0 :(得分:1)

这就是我解决问题的方法。执行task.cancel()时,不会执行print语句。看起来有点hacky来检查字符串,所以如果有人有更好的解决方案,我会接受那个。

 ORA-04088: error during execution of trigger 'EDIWEA.TRI_P_FLUSSO'

答案 1 :(得分:1)

我希望这是你可以使用的东西:

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)
    }
}