Reputation: 1110
I am using this lib for checking Reachability
And below is my sample code:
override func viewWillAppear(_ animated: Bool) {
let reachability = Reachability()!
NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: .reachabilityChanged, object: reachability)
do{
try reachability.startNotifier()
}catch{
print("could not start reachability notifier")
}
getUserDetail()
}
@objc func reachabilityChanged(note: Notification) {
let reachability = note.object as! Reachability
switch reachability.connection {
case .wifi:
internetConnectionView.isHidden = true
case .cellular:
internetConnectionView.isHidden = true
case .none:
internetConnectionView.isHidden = false
}
}
But I am not able to achieve this when i am switching wifi on and off at run time.
I don't know what I am missing.
Here is my sample project.
Upvotes: 2
Views: 163
Reputation: 71854
Faced the same issue before, to resolve it you need to declare
let reachability = Reachability()!
outside viewWillAppear
function and your code will look like:
let reachability = Reachability()!
override func viewWillAppear(_ animated: Bool) {
NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: .reachabilityChanged, object: reachability)
do{
try reachability.startNotifier()
}catch{
print("could not start reachability notifier")
}
getUserDetail()
}
Upvotes: 2