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.