William Loke
William Loke

Reputation: 377

Internet Reconnection Swift

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!

Upvotes: 3

Views: 1577

Answers (4)

Gowtham Sooryaraj
Gowtham Sooryaraj

Reputation: 3907

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()
              })
        }
    }

Upvotes: 1

Eduardo Urso
Eduardo Urso

Reputation: 296

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.

Upvotes: 0

kalpesh
kalpesh

Reputation: 1287

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.

Upvotes: 0

PPL
PPL

Reputation: 6565

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.

Upvotes: 1

Related Questions