Reachability.swift: Can only get the Notification to notice 1 change then it stops noticing them.

So I have an app I’m developing. I’d like to thank Mr Mills for his contribution with this library.

In my AppDelegate:

var reachability: Reachability!


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.


        //NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged), name: ReachabilityChangedNotification, object: nil)

        reachability = Reachability.init()
        do {
            try reachability.startNotifier()
            print("setting up notifier")
        } catch {
            print("notifier failed.")
        }
            return true
    }

Then I have a View Controller where I set up the reference to the notifier and try to listen for the changes to it. It will change the label when I disconnect the WiFi however when it reconnectes there is no change to the label and the notifier doesn’t fire off the function.

class contactPrefsViewController: UIViewController {

    @IBOutlet weak var labelConnected: UILabel!
    var reachability2: Reachability!


    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewDidAppear(_ animated: Bool) {

        NotificationCenter.default.addObserver(self, selector: #selector(self.reachabilityChanged), name: ReachabilityChangedNotification, object: nil)

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func reachabilityChanged(notify:Notification){
        let reachability2 = notify.object as! Reachability
        print("doing notification");
        if reachability2.isReachable{
            self.labelConnected.text = "connected"
            print("connected")
        }else{
            self.labelConnected.text = "not connected"
            print("not Connected")
        }
    }

Any advice appreciated.

About this issue

  • Original URL
  • State: open
  • Created 8 years ago
  • Reactions: 5
  • Comments: 15

Most upvoted comments

i’m currently using Alamofire’s NetworkReachabilityManager

func checkNetworkReachability() {
        let mgr  = NetworkReachabilityManager()
        mgr?.listener = { status in
            print("Network Status Changed: \(status)")
            kNetworkNotConnected = mgr?.isReachable == true ? false : true
        }
        mgr?.startListening()
    }