请求超时 NSURLSession
Request Timeout NSURLSession
你好我使用下面的代码向服务器发送请求。如何在此函数中添加超时
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")
请任何人建议我如何在我的函数中添加超时的正确解决方案
NSMutableURLRequest 也有这个方法:
let request = NSMutableURLRequest(URL: NSURL(string: url)!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5)
您无法修改您的请求,因为出于某种原因您选择了不可变选项。由于 NSMutableURLRequest 是 NSURLRequest 的子类,您可以使用完全相同的初始化程序 init(URL:cachePolicy:timeoutInterval:)
来创建 mutable 实例并设置默认超时。然后根据需要配置(改变)这个请求。
let request = NSMutableURLRequest(URL: url!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5.0)
使用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)
NSMutableRequest
有一个 属性 timeoutInterval
可以设置。
Here 是 Apple 的文档,向您展示了如何设置超时。
他们说
If during a connection attempt the request remains idle for longer than the timeout interval, the request is considered to have timed out. The default timeout interval is 60 seconds.
请注意,超时确实不保证如果网络调用网络调用将被终止未 在超时时间内完成。
即:假设您将超时设置为 60 秒。
连接可能仍处于活动状态,并且在 60 秒后不会终止。如果在 60 秒的完整时间内没有 数据传输,则会发生超时。
E.g. Consider the following scenario This does NOT incur a timeout
- t=0 到 t=59 秒 => 无数据传输 (总共 59 秒)
- t=60 到 t=62 => 一些数据在 t=60 秒到达 (总共 2 秒)
- t=63 到 t=100 => 无数据传输(总共 37 秒)
- t=100 to t=260 => 剩余数据传输并完成网络
请求 (总计 160 秒)
Now consider the following scenario. Timeout occurs at t=120
- t=0 到 t=59 秒 => 一些数据传输直到 t=59 (总共 59 秒)
- t=60 到 t=120 => 无数据传输(总共 60 秒)
你好我使用下面的代码向服务器发送请求。如何在此函数中添加超时
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")
请任何人建议我如何在我的函数中添加超时的正确解决方案
NSMutableURLRequest 也有这个方法:
let request = NSMutableURLRequest(URL: NSURL(string: url)!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5)
您无法修改您的请求,因为出于某种原因您选择了不可变选项。由于 NSMutableURLRequest 是 NSURLRequest 的子类,您可以使用完全相同的初始化程序 init(URL:cachePolicy:timeoutInterval:)
来创建 mutable 实例并设置默认超时。然后根据需要配置(改变)这个请求。
let request = NSMutableURLRequest(URL: url!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5.0)
使用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)
NSMutableRequest
有一个 属性 timeoutInterval
可以设置。
Here 是 Apple 的文档,向您展示了如何设置超时。
他们说
If during a connection attempt the request remains idle for longer than the timeout interval, the request is considered to have timed out. The default timeout interval is 60 seconds.
请注意,超时确实不保证如果网络调用网络调用将被终止未 在超时时间内完成。
即:假设您将超时设置为 60 秒。 连接可能仍处于活动状态,并且在 60 秒后不会终止。如果在 60 秒的完整时间内没有 数据传输,则会发生超时。
E.g. Consider the following scenario This does NOT incur a timeout
- t=0 到 t=59 秒 => 无数据传输 (总共 59 秒)
- t=60 到 t=62 => 一些数据在 t=60 秒到达 (总共 2 秒)
- t=63 到 t=100 => 无数据传输(总共 37 秒)
- t=100 to t=260 => 剩余数据传输并完成网络 请求 (总计 160 秒)
Now consider the following scenario. Timeout occurs at t=120
- t=0 到 t=59 秒 => 一些数据传输直到 t=59 (总共 59 秒)
- t=60 到 t=120 => 无数据传输(总共 60 秒)