ios取消NSURLConnection Swift

时间:2016-07-14 21:47:33

标签: ios swift asynchronous nsurlconnection

我有以下代码:

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

当向用户显示图像幻灯片时,它在后台运行,它基本上下载了更多要显示的图像,并将它们附加到图像阵列。问题是用户可以随时退出幻灯片,在这种情况下我需要取消此NSURLConnection。我有一个在用户想要退出幻灯片时执行的功能,但是我不确定要添加哪些代码来正确取消此连接。

1 个答案:

答案 0 :(得分:6)

NSURLConnection' sendAsynchronousRequest不是可取消的请求。但是,NSURLConnection已被弃用,您应该使用NSURLSessionNSURLSession' dataTask可取消。

所以,而不是:

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

您可以使用:

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

而且,如果你需要取消它,你可以task.cancel()