I have a scenario where i need to send a request to server which is a simpler thing when we are having internet connection available at the time of request.
But i need to write a retry mechanism in such a way that if currently internet connection is not available and when internet connection comes back we should re-send the request to server. How to achieve the same in iOS as in case of android pretty easy and doable with different ways. New to iOS development so any example would be great help.
I am using objective C
If you're using Alamofire then their is RequestRetrier
protocol which lets you retry network requests (documentation link)
class RetryHandler: RequestAdapter, RequestRetrier {
public func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: RequestRetryCompletion) {
if let response = request.task.response as? HTTPURLResponse, response.statusCode == 401 {
completion(true, 1.0) // retry after 1 second
} else {
completion(false, 0.0) // don't retry
}
}
}
let sessionManager = SessionManager()
sessionManager.retrier = RetryHandler()
sessionManager.request(urlString).responseJSON { response in
debugPrint(response)
}
If you're using URLSession then in iOS 11 apple has added waitsForConnectivity flag which wait until network connectivity is available before trying the connection
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 120
configuration.timeoutIntervalForResource = 120
if #available(iOS 11, *) {
configuration.waitsForConnectivity = true
}
let session = URLSession(configuration: configuration)
Note: The session only waits when trying the initial connection. If the network drops after making the connection you get back an error via the completion handler or session delegate as with iOS 10. How long it will depends upon resource timeoutIntervalForResource
or finally you can use Reachability to detect the network changes and retry network request again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With