Created
August 26, 2022 05:46
-
-
Save SaurabhPrajapati/391327ba166cfe95fa14b1a4241c88b8 to your computer and use it in GitHub Desktop.
NetworkReachability based using Network framework with NWPathMonitor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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