Home > OS >  How to use NWPathMonitor with Alamofire?
How to use NWPathMonitor with Alamofire?

Time:09-24

I have currently a NetworkManager class that utilizes Alamofire and handle network requests. Additionally I have a MonitorManager class that returns internet connection status. So I would like to make generic implementation that every request should establish internet connection, otherwise an error pop up will appear. How can I acquire this?

CodePudding user response:

This is not the recommended way to use NWPathMonitor. Apple recommends that you issue your network requests like normal and, if they fail with particular connectivity errors, use the path monitor to wait for the connectivity to return, then reissue the request. Unfortunately Alamofire doesn't have that functionality out of the box so you'll need to integrate the two yourself. Fortunately, Alamofire's RequestRetrier provides an appropriate hook. You could do something like this:

struct PathAwaitingRetrier: RequestRetrier {
    // Take a reference to your path monitor.

    func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) {
        // Check error to see if it's a connectivity error.
        // If so, add an observer to the path monitor which will 
        // call completion(.retry) when connectivity is restored.
        // If not, call completion(.doNotRetry).
    }
}
  • Related