When trying to check internet connectivity I have a problem. When using alamofire NetworkReachabilityManager on a wifi with no internet like so:
import Alamofire
class Connectivity {
class func isConnectedToInternet() ->Bool {
return NetworkReachabilityManager()!.isReachable
}
}
This is the implementation:
if Connectivity.isConnectedToInternet() {
print("Yes! internet is available.")
} else {
print("No! internet is not available.")
}
I am getting: "Yes! internet is available." when there is no active internet connection (checked with Safari).
Tried also this one with Reachability:
import Reachability
class ReachabilityManager: NSObject {
var reachability: Reachability!
static let sharedInstance: NetworkManager = { return NetworkManager() }()
override init() {
super.init()
reachability = Reachability()!
NotificationCenter.default.addObserver(
self,
selector: #selector(networkStatusChanged(_:)),
name: .reachabilityChanged,
object: reachability
)
do {
try reachability.startNotifier()
} catch {
print("Unable to start notifier")
}
}
@objc func networkStatusChanged(_ notification: Notification) {
// Do something globally here!
}
static func stopNotifier() -> Void {
do {
try (NetworkManager.sharedInstance.reachability).startNotifier()
} catch {
print("Error stopping notifier")
}
}
static func isReachable(completed: @escaping (NetworkManager) -> Void) {
if (NetworkManager.sharedInstance.reachability).connection != .none {
completed(NetworkManager.sharedInstance)
}
}
static func isUnreachable(completed: @escaping (NetworkManager) -> Void) {
if (NetworkManager.sharedInstance.reachability).connection == .none {
completed(NetworkManager.sharedInstance)
}
}
static func isReachableViaWWAN(completed: @escaping (NetworkManager) -> Void) {
if (NetworkManager.sharedInstance.reachability).connection == .cellular {
completed(NetworkManager.sharedInstance)
}
}
static func isReachableViaWiFi(completed: @escaping (NetworkManager) -> Void) {
if (NetworkManager.sharedInstance.reachability).connection == .wifi {
completed(NetworkManager.sharedInstance)
}
}
}
The implementation is:
NetworkManager.isReachable { networkManagerInstance in
print("Network is available")
}
NetworkManager.isUnreachable { networkManagerInstance in
print("Network is Unavailable")
}
What am I doing wrong?
How did you check connection? did you try to reach any host something like below.
do {
Network.reachability = try Reachability(hostname: "www.google.com")
do {
try Network.reachability?.start()
} catch let error as Network.Error {
print(error)
} catch {
print(error)
}
} catch {
print(error)
}