简体   繁体   English

ios取消NSURLConnection Swift

[英]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 . 问题是用户可以随时退出幻灯片放映,在这种情况下,我需要取消此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. NSURLConnectionsendAsynchronousRequest不可取消请求。 But NSURLConnection is deprecated, anyway, and you should use NSURLSession . 但是无论如何, NSURLConnection已被弃用,您应该使用NSURLSession And NSURLSession 's dataTask is cancelable. 并且NSURLSessiondataTask是可取消的。

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() . 而且,如果需要取消它,可以执行task.cancel()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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