Search code examples
iosobjective-creachabilityconnectivity

Connectivity Internet - how can I try to connect for 5 secs and then give up?


I would like to connect to the Internet. If after 5 secs I haven't connected (using Reachability) I want to abort. Is this possible ?


Solution

  • NSTimer with a callback for 1 second and a counter. If 5 attempts fail, 5 seconds has passed.

    Something like:

    var timerCounter = 0
    var timer : NSTimer?
    
    func shouldAttemptConnection() {
      timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "attemptConnection", userInfo: nil, repeats: true)
      self.attemptConnection()
    }
    
    func attemptConnection() {
      if Reachability.isReachable() {
         // Handle success code
    
      } else if ++timerCounter >= 5 {
         // Handle timeout code
    
      } else {
         // Try again
         return
      }
    
      self.invalidateTimer()
    }
    
    func invalidateTimer() {
      timer?.invalidate()
      timer = nil
      timerCounter = 0
    }