在某些網站上,下面的方法無限期掛起,我想取消請求時,它需要太長時間,我認爲timeoutIntervalForRequest
和timeoutIntervalForResource
將控制這一點,但設置其中任何一個doesn似乎沒有任何效果。當請求過長時取消NSURLSession數據任務
這是一個例子網站,請求掛起無限期:http://www.samtoft.co.uk/showpic.php?id=542&order=&search=#header
// 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()
sessionConfig.timeoutIntervalForRequest = 10.0
sessionConfig.timeoutIntervalForResource = 10.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 redirectError = 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) + \(redirectError)")
callback(failure)
}
}
}
loadDataTask!.resume()
}
編輯:對於誰是有同樣的問題,我是人,問題是,我是佔成功案例和錯誤的情況下,而不是當請求返回響應,所以我加了如下:
if response == nil {
print("NO RESPONSE \(myURL)")
let noResponse = Result.NoResponse("NO RESPONSE")
callback(noResponse)
}
你在調用'dataTaskWithURL:completion:'。這是一種頭腦簡單的方式。如果使用'dataTaskWithURL'和一個委託,會發生什麼? – matt