3

My app currently shows an alert if there isn't an internet connection. However, I would like it to reconnect automatically once internet connection is detected without user needing to restart the app.

the code for I used currently is

if Reachability.isConnectedToNetwork() == true {
    print("Internet Connection Available!")
} else {
    let alertController = UIAlertController(title: "Alert",
                                            message: "Internet Connection not Available!",
                                            preferredStyle: UIAlertControllerStyle.alert)
    alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil))
    self.present(alertController, animated: true, completion: nil)
}

anyone can give some advice? if my question isn't clear, do let me know. Thx guys!

PPL
  • 6,357
  • 1
  • 11
  • 30
William Loke
  • 377
  • 1
  • 4
  • 25
  • Possibly you can make it move to a different No internet screen where there would be a button, On clicking the button you check whether internet is there or not, If internet found the pop back to previous VC. – Abhirajsinh Thakore Apr 13 '18 at 07:35
  • You can use Alamofire for this purpose. Please see [this answer](https://stackoverflow.com/a/35432328/7842542) for details – Malik Apr 13 '18 at 07:37
  • You can use Alamofire.reachability they had implemented a closure to notify when the network state has changed – Reinier Melian Apr 13 '18 at 07:41
  • i don't know sure ; when your network not available then call one detaly method for delay to check current function again? – Gowtham Sooryaraj Apr 13 '18 at 07:48

4 Answers4

1

It's Working well for me

func myconn(){
     if Reachability.isConnectedToNetwork() == true
        {
            print("Internet Connection Available!")
        }
        else
        {
            let alertController = UIAlertController(title: "Alert", message:
                "Internet Connection not Available!", preferredStyle: UIAlertControllerStyle.alert)
            alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil))

            self.present(alertController, animated: true, completion: nil)
              DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
               self.myconn()
              })
        }
    }
Gowtham Sooryaraj
  • 3,639
  • 3
  • 13
  • 22
1

You should addObserver of Reachability in applicationDidFinishLaunching method, like below,

NotificationCenter.default.addObserver(self, selector: #selector(networkStatusChanged(_:)), name: NSNotification.Name(rawValue: ReachabilityStatusChangedNotification), object: nil)
Reach().monitorReachabilityChanges()

Implement this method as well,

@objc func networkStatusChanged(_ notification: Notification) {
    let userInfo = (notification as NSNotification).userInfo
    if let status = userInfo?["Status"] as? String, status == "Offline" {
        //Display alert view
    } else if let status = userInfo?["Status"] as? String, status != "Unknown" {
        //Internet connection is active
    }
}

Above function automatically triggers call when there is active internet connection.

PPL
  • 6,357
  • 1
  • 11
  • 30
0

You need to add addObserver of ReachabilityChangedNotification.

NSNotificationCenter.defaultCenter().addObserver(self, selector:"checkForReachability:", name: ReachabilityChangedNotification, object: nil);
self.reachability = Reachability.reachabilityForInternetConnection();
self.reachability.startNotifier();



 func checkForReachability(notification:NSNotification)
    {
        let networkReachability = notification.object as Reachability;
        var remoteHostStatus = networkReachability.currentReachabilityStatus()

        if (remoteHostStatus.value == NotReachable.value)
        {
            print("Not Reachable")
        }
        else if (remoteHostStatus.value == ReachableViaWiFi.value)
        {
            print("Reachable via Wifi")
        }
        else
        {
            print("Reachable")
        }
    }

Whenever change the network it will notify you.

kalpesh
  • 1,285
  • 1
  • 17
  • 30
0

You could also use RxSwift to observe you reachability notifications and deal with the changes whenever you get a new connection state.

like this:

    var isOnline: Bool {
       guard let reachability = reachability else { return false }
       return reachability.currentReachabilityStatus.isOnline
    }

    func connectionStatus() -> Observable<ConnectionStatus> {
       return notificationCenter
          .rx
          .notification(ReachabilityChangedNotification)
          .observeOn(observeScheduler)
          .flatMap { notification -> Observable<ConnectionStatus> in
              guard let reachability = notification.object as? Reachability else {
                return .empty()
              }

              return .just(ConnectionStatus(isOnline: reachability.isReachable))
          }
          .startWith(ConnectionStatus(isOnline: isOnline))
          .distinctUntilChanged()
}

This way you'll be observing any changes in the connection and can react to it the you you want.

You just need to Subscribe to the Observable<ConnectionStatus> and then you can decide if you want the user to trigger a new reconnection flow or if you would retry a few times before displaying it.

Eduardo Urso
  • 296
  • 3
  • 6