我有一個MySession類,我打電話來獲取網站的重定向的URL。在我的ViewController
中,當用戶通過ViewDidDisappear
導航回ViewController
時,我想取消會話。我知道NSURLSessionTasks
有一個.cancel
方法,但我想不出最好的方法來做到這一點。我可以將當前任務存儲在Singleton中,但認爲必須有更好的方法?如何取消Swift中另一個類的NSURLSession?
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
}
從我的觀點可以通過委託模式進行委託。 –
你能詳細說一下怎麼做?我試過,但當我設置委託,即'弱var委託= TaskCancelAble?'我得到「實例成員委託不能設置類型MySession」 – GarySabo