7

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

Jitesh Upadhyay
  • 5,244
  • 2
  • 25
  • 43

2 Answers2

7

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.

Suhit Patil
  • 11,748
  • 3
  • 50
  • 60
1

If you are using Alamofire in your app, you could do this:

import Alamofire

let reachabilityManager = NetworkReachabilityManager()
reachabilityManager?.listener = { [weak self] status in
    var isReachable = false
    switch status {
    case .notReachable, .unknown:
        isReachable = false
        break
    case .reachable:
        isReachable = true
        break
    }
    // Notify the rest of the app (perhaps use a Notification)
        }
reachabilityManager?.startListening()

If you are not using Alamofire, then check the question and answers here on using Reachability

Objective-C vs Swift will not be much different, you can follow the exact same approach, just translate it to Objective-C.

Cloud9999Strife
  • 3,102
  • 3
  • 30
  • 43