Skip to content

Instantly share code, notes, and snippets.

@SaurabhPrajapati
Created August 26, 2022 05:46
Show Gist options
  • Save SaurabhPrajapati/391327ba166cfe95fa14b1a4241c88b8 to your computer and use it in GitHub Desktop.
Save SaurabhPrajapati/391327ba166cfe95fa14b1a4241c88b8 to your computer and use it in GitHub Desktop.
NetworkReachability based using Network framework with NWPathMonitor
//
// NetworkReachability.swift
// Claire
//
// Created by Saurabh on 27/07/22.
//
import Foundation
import Network
import Combine
class NetworkReachability {
private let networkPathMonitor: NWPathMonitor
@Published var connectionAvailable = false
init() {
networkPathMonitor = NWPathMonitor()
startNetworkMonitoring()
}
private func startNetworkMonitoring() {
guard
networkPathMonitor.queue == nil
else {
Logger.warn("Trying to start monitoring network multiple time")
return
}
let queue = DispatchQueue(label: "com.clairehealth.app.ios")
self.networkPathMonitor.pathUpdateHandler = { [weak self] path in
self?.connectionAvailable = path.status == .satisfied
}
self.networkPathMonitor.start(queue: queue)
}
func networkAvailable() -> Bool {
return networkPathMonitor.currentPath.status == .satisfied
}
func networkAvailableViaWifi() -> Bool {
return networkPathMonitor.currentPath.usesInterfaceType(.wifi)
}
func networkAvailableViaCellular() -> Bool {
return networkPathMonitor.currentPath.usesInterfaceType(.cellular)
}
func stopNetworkMonitoring() {
self.networkPathMonitor.cancel()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment