I want functionality similar to AFNetworking
in Objective-C with Alamofire NetworkReachabilityManager in Swift:
//Reachability detection
[[AFNet
Swift 5: No need for listener object . Just we need to call the closure :
struct Network {
let manager = Alamofire.NetworkReachabilityManager()
func state() {
manager?.startListening { status in
switch status {
case .notReachable :
print("not reachable")
case .reachable(.cellular) :
print("cellular")
case .reachable(.ethernetOrWiFi) :
print("ethernetOrWiFi")
default :
print("unknown")
}
}
}
}
You can start using this function like :
Network().state()
I found the answer myself i.e by just writing a listener with closure as mentioned below:
let net = NetworkReachabilityManager()
net?.listener = { status in
if net?.isReachable ?? false {
switch status {
case .reachable(.ethernetOrWiFi):
print("The network is reachable over the WiFi connection")
case .reachable(.wwan):
print("The network is reachable over the WWAN connection")
case .notReachable:
print("The network is not reachable")
case .unknown :
print("It is unknown whether the network is reachable")
}
}
net?.startListening()
Alamofire 5 and above
import Alamofire
// MARK: NetworkReachability
final class NetworkReachability {
static let shared = NetworkReachability()
private let reachability = NetworkReachabilityManager(host: "www.apple.com")!
typealias NetworkReachabilityStatus = NetworkReachabilityManager.NetworkReachabilityStatus
private init() {}
/// Start observing reachability changes
func startListening() {
reachability.startListening { [weak self] status in
switch status {
case .notReachable:
self?.updateReachabilityStatus(.notReachable)
case .reachable(let connection):
self?.updateReachabilityStatus(.reachable(connection))
case .unknown:
break
}
}
}
/// Stop observing reachability changes
func stopListening() {
reachability.stopListening()
}
/// Updated ReachabilityStatus status based on connectivity status
///
/// - Parameter status: `NetworkReachabilityStatus` enum containing reachability status
private func updateReachabilityStatus(_ status: NetworkReachabilityStatus) {
switch status {
case .notReachable:
print("Internet not available")
case .reachable(.ethernetOrWiFi), .reachable(.cellular):
print("Internet available")
case .unknown:
break
}
}
/// returns current reachability status
var isReachable: Bool {
return reachability.isReachable
}
/// returns if connected via cellular
var isConnectedViaCellular: Bool {
return reachability.isReachableOnCellular
}
/// returns if connected via cellular
var isConnectedViaWiFi: Bool {
return reachability.isReachableOnEthernetOrWiFi
}
deinit {
stopListening()
}
}
How to use:
Call NetworkReachability.shared. startListening()
from AppDelegate
to start listening for reachability changes
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
NetworkReachability.shared.startListening()
// window and rootviewcontroller setup code
return true
}
}
Apple says to use a struct instead of a class when you can. So here's my version of @rmooney and @Ammad 's answers, but using a struct instead of a class. Additionally, instead of using a method or function, I am using a computed property and I got that idea from this Medium post by @Abhimuralidharan. I'm just putting both the idea of using a struct instead of a class (so you don't have to have a singleton) and using a computed property instead of a method call together in one solution.
Here's the struct NetworkState:
import Foundation
import Alamofire
struct NetworkState {
var isConnected: Bool {
// isReachable checks for wwan, ethernet, and wifi, if
// you only want 1 or 2 of these, the change the .isReachable
// at the end to one of the other options.
return NetworkReachabilityManager(host: www.apple.com)!.isReachable
}
}
Here is how you use it in any of your code:
if NetworkState().isConnected {
// do your is Connected stuff here
}
Solution for swift 4* + swift 5* and Alamofire 4.5+
CREATE a
NetworkReachabilityManager
class fromAlamofire
and configure thecheckNetwork()
method
import Alamofire
class Connectivity {
class func checkNetwork() ->Bool {
return NetworkReachabilityManager()!.isReachable
}
}
USAGE
switch Connectivity.checkNetwork() {
case true:
print("network available")
//perform task
case false:
print("no network")
}
To create NetworkManager Class as follows (For SWIFT 5)
import UIKit
import Alamofire
class NetworkManager {
static let shared = NetworkManager()
let reachabilityManager = Alamofire.NetworkReachabilityManager(host: "www.apple.com")
func startNetworkReachabilityObserver() {
reachabilityManager?.startListening(onUpdatePerforming: { status in
switch status {
case .notReachable:
print("The network is not reachable")
case .unknown :
print("It is unknown whether the network is reachable")
case .reachable(.ethernetOrWiFi):
print("The network is reachable over the WiFi connection")
case .reachable(.cellular):
print("The network is reachable over the cellular connection")
}
})
}
}
And the usage will be like
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// add network reachability observer on app start
NetworkManager.shared.startNetworkReachabilityObserver()
return true
}
}