Search code examples
iosnetwork-programmingreachability

Monitor the status of the Internet Swift


I know how to check the network connectivity through Reachability.Swift. I want to achieve some thing like, in a view controller, if internet check in the background after the view load, I even know we can start a NSTimer so that it will check lets after 5 minutes and each time call Reachability class to check for the connectivity.

My question is is there any other theory available for this,

I have seen a Library for this Link to Lib

However I want to know if someone achieve this neatly in Swift!!!


Solution

  • Swift 2.0 - Check Network Using Reachability, NSNotification

    AppDelegate.swift
    
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool 
    {
          NSNotificationCenter.defaultCenter().addObserver(self, selector:"checkNetworkStatus", name: ReachabilityChangedNotification, object: nil);
    
     do{self.reachability = try Reachability.reachabilityForInternetConnection()}catch{}
     do{try self.reachability.startNotifier()}catch{}
     self.checkNetworkStatus()
    
     return true
    }
    

    Declare networkStatus variable

    var networkStatus : Reachability.NetworkStatus!
    checkNetworkStatus() Function
    
    func checkNetworkStatus()
    {
      networkStatus = reachability.currentReachabilityStatus
    
      if (networkStatus == Reachability.NetworkStatus.NotReachable)
      {
        print("Not Reachable")
      }
      else
     {
        print("Reachable")
     }
     }
    

    OtherClass.Swift

    let delegate = UIApplication.sharedApplication().delegate as!  AppDelegate
    
     if (delegate.networkStatus!=Reachability.NetworkStatus.NotReachable)
     {
        // Call Webservice     
     }
     else
     {
        delegate.checkNetworkStatus()  //Not Reachable print  
     }