title: How to cancel on-going HTTP request in Swift?
body: <p>My code does <strong>GET</strong> request like this:</p>
  
  <pre><code>dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -&gt; Void in
      // ...
  
      let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
          if error != nil {
              println("error = \(error)")
              return
          }
  
          if let HTTPresponse = response as? NSHTTPURLResponse {
              if HTTPresponse.statusCode == 200 { // Successfully got response
                  var err: NSError?
                  if let json = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: &amp;err) as? [String : AnyObject] {
                      // Success decoding JSON
                  } else {
                      // Failed -&gt; stop activity indicator
                      dispatch_async(dispatch_get_main_queue(), { () -&gt; Void in
                          self.activityIndicator.stopAnimating()
                      })
                  }
              }
              task.resume()
          })
      }
  }
  </code></pre>
  
  <p>If <code>viewWillDisappear()</code> gets called before the request finishes, I want to stop the request.</p>
  
  <p>Right now, it seems like the view doesn't disappear before the request finishes. Is there a way to cancel the ongoing <strong>GET/POST</strong> request?</p>