请求超时NSURLSession

时间:2016-02-16 08:06:59

标签: ios swift nsurlconnection nsurl nsurlsession

你好我用下面这段代码向Server发送请求。如何在此函数中添加超时

static func postToServer(url:String,var params:Dictionary<String,NSObject>, completionHandler: (NSDictionary?, String?) -> Void ) -> NSURLSessionTask {


        let request = NSMutableURLRequest(URL: NSURL(string: url)!)


        let session = NSURLSession.sharedSession()

        request.HTTPMethod = "POST"

    if(params["data"] != "get"){
        do {

            let data = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)

            let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)!
            print("dataString is  \(dataString)")

            request.HTTPBody = data


        } catch {
            //handle error. Probably return or mark function as throws
            print("error is \(error)")
            //return
        }

    }
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        let task = session.dataTaskWithRequest(request) {data, response, error -> Void in
            // handle error

            guard error == nil else { return }
            request.timeoutInterval = 10


           print("Response: \(response)")
            let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
             completionHandler(nil,"Body: \(strData!)")
          //print("Body: \(strData!)")

            let json: NSDictionary?
            do {
                json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
            } catch let dataError {
                // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
                print(dataError)
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
              print("Error could not parse JSON: '\(jsonStr)'")
                completionHandler(nil,"Body: \(jsonStr!)")

                // return or throw?
                return
            }


            // The JSONObjectWithData constructor didn't return an error. But, we should still
            // check and make sure that json has a value using optional binding.
            if let parseJSON = json {
                // Okay, the parsedJSON is here, let's get the value for 'success' out of it

                completionHandler(parseJSON,nil)
                //let success = parseJSON["success"] as? Int
                //print("Succes: \(success)")
            }
            else {
                // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("Errors could not parse JSON: \(jsonStr)")
                completionHandler(nil,"Body: \(jsonStr!)")
            }

        }

        task.resume()
        return task
    }

我也做了一些搜索,我开始知道要使用这个功能

let request = NSURLRequest(URL: url!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5.0)

而不是

let request = NSMutableURLRequest(URL: NSURL(string: url)!)

但问题是如果我使用上面的函数那么我就不能设置这些变量

request.HTTPBody = data
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

请有人建议我正确解决如何在我的功能中添加超时

4 个答案:

答案 0 :(得分:3)

您无法修改您的请求,因为出于某种原因您使用了不可变选项。由于NSMutableURLRequest是NSURLRequest的子类,因此您可以使用完全相同的初始化程序init(URL:cachePolicy:timeoutInterval:)来创建可变实例并设置默认超时。然后根据需要配置(变更)此请求。

let request = NSMutableURLRequest(URL: url!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5.0)

答案 1 :(得分:2)

NSMutableRequest有一个您可以设置的属性timeoutInterval。  Here是Apple的文档,向您展示如何设置超时。

他们已声明

  

如果在连接尝试期间请求保持空闲的时间超过超时间隔,则认为请求已超时。默认超时间隔为 60

请注意,超时 保证如果网络通话 在超时内完成。

ie:假设您将超时设置为60秒。 连接可能仍处于活动状态,并且在60秒后不会终止。如果在60秒的完整时间段内有数据传输,则会发生超时。

  

E.g。 请考虑以下情况 这不会导致超时

  • t = 0到t = 59秒=&gt;没有数据传输(总共59秒)
  • t = 60至t = 62 =&gt;一些数据到达t = 60s (总共2秒)
  • t = 63至t = 100 =&gt;没有数据传输(总共37秒)
  • t = 100至t = 260 =&gt;剩余数据传输并完成网络 要求(总共160秒)
  

现在考虑以下情况超时发生在t = 120

  • t = 0到t = 59秒=&gt;一些数据传输直到t = 59 (总共59秒)
  • t = 60至t = 120 =&gt;没有数据传输(总共60秒)

答案 2 :(得分:1)

使用 NSURLSessionConfiguration 指定超时,

let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
sessionConfig.timeoutIntervalForRequest = 30.0 //Request Timeout interval 30 sec
sessionConfig.timeoutIntervalForResource = 30.0 //Response Timeout interval 30 sec

let session  = NSURLSession(configuration: sessionConfig)

答案 3 :(得分:0)

NSMutableURLRequest也有这个方法:

let request = NSMutableURLRequest(URL:  NSURL(string: url)!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5)