2015-06-16 29 views
1

使用根据此线程首选的NSURLSession即可。 How to make an HTTP request in Swift?如果用户在swift iOS中点击两次,则取消NSURLSession

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语句仍然被执行(即在.cancel()和NSDomainError之后)。我如何安全地取消这个请求(NSURLSessionDataTask),而不触发print语句,或者甚至可能?编辑: 只是要清楚。网址可能相同,我想取消第一个请求。

+0

是否打印语句或'NSDomainError'指定任务被取消?如果是这样,只需打开它并忽略该错误,因为您期待它。 – keithbhunter

+1

[如何在NSURLSession中查找和取消任务?](http://stackoverflow.com/questions/23518690/how-to-find-and-cancel-a-task-in-nsurlsession) – LoVo

+0

@LoVo没有什么不同的问题(他在找到任务时遇到问题),我也问过如何快速做到这一点。 – Zeezer

回答

0

这就是我解决问题的方法。当执行task.cancel()时,print语句不会被执行。似乎有点古怪检查一个字符串,所以如果任何人有更好的解决方案,我会接受一个。

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() 
+0

以避免检查字符串我做过: 如果让err =错误为? NSURLError如果错误== NSURLError.Cancelled {“❌请求取消” } } – scord

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

如果您使用'download!.resume()'而不是'download?.resume()'和其他),因为你已经把它包装在一个'nil'检查中了吗? –

相关问题