Alk
Alk

Reputation: 5567

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
    request.HTTPBody=data
    request.HTTPShouldHandleCookies=false
    let queue:NSOperationQueue = NSOperationQueue()
    NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
        do {
            ....code.....

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 NSURLConnection. 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.

Upvotes: 2

Views: 576

Answers (1)

Rob
Rob

Reputation: 438467

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 {
        ....code.....
    } 
}

You can use:

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

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

Upvotes: 6

Related Questions