Checking internet connection in swift using Alamofire
1 min readMar 25, 2017
I am seeing medium.com as a medium to save my code in remote so that it is accessible from anywhere. This may or may not be helpful for others. :-)
For swift 3+ and Alamofire 4.4 , I created 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 Alamofireclass Connectivity {
class func isConnectedToInternet() ->Bool {
return NetworkReachabilityManager()!.isReachable
}
}
Usage:
if Connectivity.isConnectedToInternet() {
print("Yes! internet is available.")
// do some tasks..
}
EDIT: Since swift is encouraging computed properties, you can change the above function like:
import Foundation
import Alamofire
class Connectivity {
class var isConnectedToInternet:Bool {
return NetworkReachabilityManager()!.isReachable
}
}
and use it like:
if Connectivity.isConnectedToInternet {
print("Yes! internet is available.")
// do some tasks..
}
Thanks. !