1

I want to implement the connection retry in NSURLSession. Is there any parameter we need to set to achieve this like 'timeoutIntervalForRequest' and NSURLSession takes the responsibility to retry the connection.

If there is no any parameter for this, how can we achieve this?

My current code is as follows:

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
}

When response code is not 200 then this function should retry the connection again. Can I do the same.

Amit Raj
  • 1,358
  • 3
  • 22
  • 47

1 Answers1

-1

Please check the answer of this 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()
}

You can also use the following default iOS function. It provide a replacement request body stream if the task needs to resend a request that has a body stream because of an authentication challenge or other recoverable server error.

Check these Link/Link for reference

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

Hope this might be helpful.

Community
  • 1
  • 1
Karlos
  • 1,653
  • 18
  • 36