Search code examples
iosswiftreachability

Detect the network at launch & resuming to avoid crash with ReachabilitySwift


I'm working on an iOS App in Swift1.2 and my app is crashing when there is no network.

So i would like to detect if i have network. But i would like to be able to know that at any moment, i mean when the app start or when it's resuming from the background etc. For what i saw i should write my code in the AppDelegate.swift

To perform that i'm using ReachabilitySwift but i'm not succeeding using it.

Beside avoiding the app to crash, the goal is also to print a banner displaying to the user the information that he have no network like the Facebook iOS App do. But that i'm close to it.

Thanks for you help and guidance in the Swift World


Solution

  • Reachability is not guaranteed that will bring you the results at the exact moment, since it's totally asynchronous. Your app shouldn't wait for Reachability results to perform connection, there is something wrong because it shouldn't crash.

    What you need to do it's add an NSNotification on your AppDelegate, to get notified when your Reachability changes.

    From the documentation

    You can add this on your didFinishLaunchingWithOptions

    let reachability = Reachability.reachabilityForInternetConnection()
    
        NSNotificationCenter.defaultCenter().addObserver(self, 
                                                         selector: "reachabilityChanged:", 
                                                         name: ReachabilityChangedNotification, 
                                                         object: reachability)
    
        reachability.startNotifier()
    

    And this to show a banner, or anything you'd like to do:

    func reachabilityChanged(note: NSNotification) {
    
            let reachability = note.object as! Reachability
    
            if reachability.isReachable() {
                if reachability.isReachableViaWiFi() {
                    println("Reachable via WiFi")
                } else {
                    println("Reachable via Cellular")
                }
            } else {
                println("Not reachable")
            }
        }