请求耗时太长时取消NSURLSession dataTask

时间:2016-03-01 23:47:39

标签: ios swift nsurlsession

在某些网站上,以下方法无限期挂起,我想在请求时间过长时取消该请求,我认为timeoutIntervalForRequesttimeoutIntervalForResource会控制此请求,但设置其中任何一个似乎没有任何效果。

这是一个示例网站,请求无限期挂起: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)
            }

1 个答案:

答案 0 :(得分:1)

我已将您的代码解压缩为

func getDataFromServerWithSuccess(myURL: String) {
    var loadDataTask: NSURLSessionDataTask? = nil
    let sessionConfig: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()

    //sessionConfig.timeoutIntervalForRequest = 11.0
    sessionConfig.timeoutIntervalForResource = 11.0

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

        print("end")
    }

    loadDataTask!.resume()
}

它确实对超时敏感。我想委托人可能有些问题无法正确接收响应。希望这会有所帮助。