NSURLSession 中的连接重试

Connection retry in NSURLSession

我想在NSURLSession中实现连接重试。我们是否需要设置任何参数来实现此目的,例如“timeoutIntervalForRequest”,NSURLSession 负责重试连接。

如果没有任何参数,我们如何实现?

我目前的代码如下:

func isHostConnected(jsonString:NSDictionary) -> NSDictionary
{
    let request = NSMutableURLRequest(URL: NSURL(string: "http://***.*.*.**:****/")!)

    do {
        request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(jsonString, options: [])
    } catch {
        //error = error1
        request.HTTPBody = nil
    }
    request.timeoutInterval = 4.0 //(number as! NSTimeInterval)
    request.HTTPMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("gzip", forHTTPHeaderField: "Accept-encoding")

    var JSONdata: AnyObject = ["" : ""] as Dictionary<String, String>
    print(JSONdata)
    let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
    var responseCode = -1

    let group = dispatch_group_create()
    dispatch_group_enter(group)

    session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
        if let httpResponse = response as? NSHTTPURLResponse {
            responseCode = httpResponse.statusCode
            let JSONresdata: AnyObject = (try! NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers))
            JSONdata = JSONresdata as! NSDictionary
        }
        dispatch_group_leave(group)
    }).resume()

    dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
    print("responseCode == 200: \(responseCode)")
    return (JSONdata) as! NSDictionary
}

当响应代码不是 200 时,此函数应重试连接。我也可以这样做吗

请检查此问题的答案link

 func someMethodWithRetryCounter(retryCounter: Int) {
     if retryCounter == 0 {
    return
 }

 retryCounter--
 var request: NSMutableURLRequest = NSMutableURLRequest.requestWithURL(NSURL.URLWithString(self.baseUrl.stringByAppendingString(path)))

 (self) weakSelf = self
 var dataTask: NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {(data: NSData, response: NSURLResponse, error: NSErrorPointer) in        var httpResponse: NSHTTPURLResponse = response
    var responseStatusCode: UInt = httpResponse.statusCode()
    if responseStatusCode != 200 {
        weakSelf.someMethodWithRetryCounter(retryCounter)
    }
    else {
        completionBlock(results["result"][symbol])
    }

})
dataTask.resume()
}

您还可以使用以下默认 iOS 函数。如果由于身份验证质询或其他可恢复的服务器错误,任务需要重新发送具有主体流的请求,它会提供替换请求主体流。

检查这些Link/Link以供参考

func URLSession(_ session: NSURLSession,
                task task: NSURLSessionTask,
   needNewBodyStream completionHandler: (NSInputStream?) -> Void)

希望这对您有所帮助。