Reputation: 6940
I use following code to check internet connection:
class Reachability {
let networkReachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.google.com")
func checkForReachability() {
self.networkReachabilityManager?.listener = { status in
print("Network Status: \(status)")
switch status {
case .notReachable:
print("no internet connection detected")
//Show error here (no internet connection)
case .reachable(_), .unknown:
print("internet connection availible")
}
}
self.networkReachabilityManager?.startListening()
}
}
When connection is exist, it successfully call block in .reachable. But in case of connection absence nothing called, why?
I call it like that (keeping reference to class, so it's not released)
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let reachabilityManager = Reachability()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
reachabilityManager.checkForReachability()
return true
}
Upvotes: 0
Views: 3856
Reputation: 82759
create the common class for check the connectivity
import Foundation
import Alamofire
class Connectivity {
class func isConnectedToInternet() -> Bool {
return NetworkReachabilityManager()!.isReachable
}
}
and call the function where you need
if !Connectivity.isConnectedToInternet() {
// show Alert
return
}
Upvotes: 7
Reputation: 2425
Create a swift class called Connectivity
. You can use NetworkReachabilityManager
class from Alamofire
and configure the isConnectedToInternet()
method as per your need. I am only checking if the device is connected to internet or not.
import Foundation
import Alamofire
class Connectivity {
class func isConnectedToInternet() ->Bool {
return NetworkReachabilityManager()!.isReachable
}
}
Usage -
if Connectivity.isConnectedToInternet() {
print("Yes! internet is available.")
// do some tasks..
}
Or you can simply do this -
if let err = error as? URLError, err.code == URLError.Code.notConnectedToInternet{
// No internet connection
}else{
// your other errors
}
Upvotes: 2