请求超时 NSURLSession [英] Request Timeout NSURLSession
问题描述
你好我使用下面的代码向服务器发送请求.如何在此函数中添加超时
hello I used this below code to send a request to Server. How can I add the timeout in this function
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
}
我也搜了一下,才知道要用这个功能
I did some search too and I came to know about to use this function
let request = NSURLRequest(URL: url!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5.0)
代替这个
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
但问题是如果我使用了上面的函数,那么我就不能设置这些变量
But problem is If I used the above function then I can't set these variables
request.HTTPBody = data
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
请任何人建议我如何在我的函数中添加超时的正确解决方案
Please anyone suggest me correct solution of how to add timeout in my function
推荐答案
您无法修改您的请求,因为出于某种原因您选择了不可变选项.由于 NSMutableURLRequest 是 NSURLRequest 的子类,因此您可以使用完全相同的初始化程序 init(URL:cachePolicy:timeoutInterval:)
来创建一个 mutable 实例并设置默认超时.然后根据需要配置(改变)这个请求.
You can't modify your request because for some reason you went with immutable option. Since NSMutableURLRequest is a subclass of NSURLRequest you can use the very same initializer init(URL:cachePolicy:timeoutInterval:)
to create an mutable instance and set default timeout. And then configure (mutate) this request as you need.
let request = NSMutableURLRequest(URL: url!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5.0)
这篇关于请求超时 NSURLSession的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!