1

我想在 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 时,此函数应再次重试连接。我可以这样做吗。

4

1 回答 1

-1

请检查此链接的答案

 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 功能。如果任务由于身份验证质询或其他可恢复的服务器错误而需要重新发送具有正文流的请求,它会提供替换请求正文流。

检查这些链接/链接以供参考

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

希望这可能会有所帮助。

于 2015-09-23T13:47:00.223 回答