如何从Swift中的另一个类中取消NSURLSession?

时间:2016-02-27 18:08:11

标签: ios swift nsurlsession

我有一个MySession类,我打电话来获取网站重定向的URL。在我的ViewController中,当用户通过ViewController导航回ViewDidDisappear时,我想取消会话。我知道NSURLSessionTasks.cancel方法,但我无法想到最好的方法。我可以将当​​前任务存储在Singleton中但是认为必须有更好的方法吗?

class MySession: NSObject, NSURLSessionDelegate {


    func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: (NSURLRequest!) -> Void) {



    }



    // fetch data from URL with NSURLSession
    class func getDataFromServerWithSuccess(myURL: String, noRedirect: Bool, callback: Result<String> -> Void) {

        var loadDataTask: NSURLSessionDataTask? = nil
        let sessionConfig: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()

        //MARK: Toggle timeout on tests
        sessionConfig.timeoutIntervalForRequest = 60.0
        sessionConfig.timeoutIntervalForResource = 60.0



        var myDelegate: MySession? = nil
        if noRedirect {
            myDelegate = MySession()
        }

        let session = NSURLSession(configuration: sessionConfig, delegate: myDelegate, delegateQueue: nil)
        loadDataTask = session.dataTaskWithURL(NSURL(string: myURL)!) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in


                if let checkedData = data {

                let success = Result.Success(NSString(data: checkedData, encoding: NSASCIIStringEncoding) as! String)


                callback(success)

                } else {

                    let error = NetworkError.FailedUrl("\(myURL) + \(error)")


                    if let request = loadDataTask?.currentRequest {

                        guard let urlExtension = request.URL?.pathExtension else {return}
                        guard let domain = request.URL?.host else {return}



                            guard let finalURLAsString = request.URL?.description else {return}
                            let failure = Result.Failure("\(finalURLAsString) + \(error)") 
                            callback(failure)

                        }

                    }

                }
        }
        loadDataTask!.resume()


    }


class MyViewController:  UIViewController {

    override func viewDidDisappear(animated: Bool) {
       //TODO:  How to stop MySession task?




               MySession.getRedirectionInfo(urlAsString)

                MySession.getDataFromServerWithSuccess(urlAsString, noRedirect: false) { result in

            //omitted for brevity 
        }

1 个答案:

答案 0 :(得分:0)

获取任务引用的另一个选项是使用该方法 来自NSURLSession的{​​{3}},其中列出会话中的所有任务以及NSURLSessionTask上的- getTasksWithCompletionHandler:属性以确定任务