简体   繁体   中英

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.

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM