mankee mankee - 2 years ago 238
Swift Question

ios Cancel NSURLConnection Swift

I have the following code:

func getStoryContent( cityID : String, completionHandler: (loaded: Bool, dataNil: Bool) -> ()) -> () {
let scriptUrl = "***"
var user_id = "nil"
if let userID = NSUserDefaults.standardUserDefaults().stringForKey("userId") {
user_id = userID
var params = ***
let myUrl = NSURL(string: scriptUrl);
let request: NSMutableURLRequest = NSMutableURLRequest(URL: myUrl!)
request.HTTPMethod = "POST"
let data = params.dataUsingEncoding(NSUTF8StringEncoding)
request.timeoutInterval = 10
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
do {

This runs in the background when displaying a slideshow of images to the user, it basically downloads more images to be displayed and appends them to the array of images. The issue is that the user can exit the slideshow at anytime, in this event I need to cancel this
. I have a function which is executed when the user wants to exit the slideshow, but I'm not sure what code to add to it to properly cancel this connection.

Rob Rob
Answer Source

NSURLConnection's sendAsynchronousRequest is not a cancelable request. But NSURLConnection is deprecated, anyway, and you should use NSURLSession. And NSURLSession's dataTask is cancelable.

So, instead of:

NSURLConnection.sendAsynchronousRequest(request, queue: queue) { response, data, error in
    do {

You can use:

let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
    do {

And, if you need to cancel it, you can do task.cancel().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download