Network reachability with Combine and Alamofire
Hello dear readers.
In this story, I will show you how to use Combine and Alamofire together to implement a network reachability helper.
It is possible to check network access in Swift using several different methods. I used the Alamofire NetworkReachabilityManager.
It can be replaced with anything else you prefer.
As a first step, I create a test project and add Alamofire as a dependency.
Next, I create a class:
import Alamofire
import Combinefinal class NetworkReachabilityHelper {}
Next, we will create an object from NetReachabilityManager* and a variable to publish network changes
private enum Constants {
static let host = "google.com"
}
var reachability = NetworkReachabilityManager(host: Constants.host)
let networkStatus = PassthroughSubject<NetworkReachabilityManager.NetworkReachabilityStatus, Error>()
We just need to add two methods to begin and stop listening to network changes for the helper to be ready.
func startListening() {
reachability?.startListening { [weak self] status in
self?.networkStatus.send(status)
}
}func stopListening() {
reachability?.stopListening()
}
This is it, we now have a helper for monitoring network status with combine.
We can add some methods to simplify our use case, for example, I created three methods for my use case
var isReachableOnCellular: Bool {
get {
return reachability?.isReachableOnCellular ?? false
}
}var isReachableOnEthernetOrWiFi: Bool {
get {
return reachability?.isReachableOnEthernetOrWiFi ?? false
}
}var isReachable: Bool {
get {
return reachability?.isReachable ?? false
}
}
The final implementation is
import Alamofire
import Combinefinal class NetworkReachabilityHelper {
static let shared = NetworkReachabilityHelper()private enum Constants {
static let host = "api1.\(Environment.domain)"
}let networkStatus = PassthroughSubject<NetworkReachabilityManager.NetworkReachabilityStatus, Error>()var reachability = NetworkReachabilityManager(host: Constants.host)var isReachableOnCellular: Bool {
get {
return reachability?.isReachableOnCellular ?? false
}
}var isReachableOnEthernetOrWiFi: Bool {
get {
return reachability?.isReachableOnEthernetOrWiFi ?? false
}
}var isReachable: Bool {
get {
return reachability?.isReachable ?? false
}
}func startListening() {
reachability?.startListening { [weak self] status in
self?.networkStatus.send(status)
}
}func stopListening() {
reachability?.stopListening()
}deinit {
stopListening()
}}
and also you can find it here.
This helper can be used by subscribing to the networkStatus variable as shown in the following example,
NetworkReachabilityHelper.shared.networkStatus
.removeDuplicates()
.sink(receiveCompletion: { _ in }, receiveValue: { [weak self] value in
\\\ check status})
.store(in: &cancelBag)
or by accessing its methods directly,
NetworkReachabilityHelper.shared.isReachable
Hopefully you will find it useful and you can use it in your project. I’d appreciate feedback on it.