Marina Marina - 26 days ago 8
Swift Question

What is the issue with ReachabilitySwift?

In my

viewDidLoad()
function I call this method:

//MARK: Reachability
func startReachability(){
//declare this property where it won't go out of scope relative to your listener
do{
let reachability = try Reachability.reachabilityForInternetConnection()

reachability.whenReachable = { reachability in
// this is called on a background thread, but UI updates must
// be on the main thread, like this:
dispatch_async(dispatch_get_main_queue()) {
if reachability.isReachableViaWiFi() {
print("Reachable via WiFi")
} else {
print("Reachable via Cellular")
}
}
}
reachability.whenUnreachable = { reachability in
// this is called on a background thread, but UI updates must
// be on the main thread, like this:
dispatch_async(dispatch_get_main_queue()) {
print("Not reachable")
}
}

try reachability.startNotifier()

} catch {
print("Unable to start notifier")
}
}


But it does not work. It calls
whenReachable()
and
whenUnreachable()
only once and when I turn Wi-Fi off and on it does nothing.

Answer Source

I needed a strong reference to Reachability instance! So I should have declared it at a class level.