I've added the following code to the viewDidLoad of my view controller:
let reachability: Reachability
do {
reachability = try Reachability.reachabilityForInternetConnection()
} catch {
print("Unable to create Reachability")
return
}
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")
}
}
do {
try reachability.startNotifier()
} catch {
print("Unable to start notifier")
}
It is notifying me of when the view loads however not when the state changes after the load. I'm wondering how to expand this so that I can have a notification anywhere in the application an not just on when the view loads as the internet may come back after a view loads.
Thanks
You should declare the reachability variable as instance variable and not only as local variable within a function. You could further use notifications to make the information available across your app. Just make sure the instance containing the reachability variable lives during the lifecycle of your app.