我写了以下函数:
func getStringFromRequest(jsonString:NSDictionary, callback: (NSDictionary, String!) -> Void) {
let request = NSMutableURLRequest(URL: NSURL(string: "https://***.*.*.**:****" )!)
var result = NSDictionary()
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(jsonString, options: [])
} catch{
//error = error1
request.HTTPBody = nil
}
request.timeoutInterval = (number as! NSTimeInterval)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("gzip", forHTTPHeaderField: "Accept-encoding")
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue:NSOperationQueue.mainQueue())
print("--------------------------------NSURLSession Request-------------------------------------------------->:\n \(jsonString)")
print(NSDate())
let task = session.dataTaskWithRequest(request){
(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode != 200 {
print("response was not 200: \(response)")
return
}
else
{
print("response was 200: \(response)")
print("Data for 200: \(data)")
result = ((try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions())) as? NSDictionary)!
print("--------------------------------NSURLSession Response-------------------------------------------------->:\n \(result)")
callback(result, nil)
return
}
}
if (error != nil) {
print("error request:\n \(error)")
print("=======================================================")
return
}
}
task.resume()
}
以上功能正常。但是我希望实现重试意味着当此函数在响应中出错时应该重试特定的时间。