Checking internet connection in swift using Alamofire

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. :-)

Image for post
Image for post

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 Alamofire
class 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. !

Written by

iOS and tvOS developer, dreamer, photographer 🤨

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store