Skip to content

Commit

Permalink
added NWPathMonitor version of NetworkMonitor
Browse files Browse the repository at this point in the history
  • Loading branch information
bryce-b committed Oct 26, 2023
1 parent f7061de commit 31dfa63
Showing 1 changed file with 72 additions and 1 deletion.
73 changes: 72 additions & 1 deletion Sources/Instrumentation/NetworkStatus/NetworkMonitor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,77 @@
#if !os(watchOS)

import Foundation


#if swift(>=5.9)
import Network
public class NetworkMonitor : NetworkMonitorProtocol {
let monitor = NWPathMonitor()
var connection : Connection = .unavailable
let lock = NSLock()

deinit {
monitor.cancel()
}

init() {
let pathHandler = { (path: NWPath) in
let availableInterfaces = path.availableInterfaces
let wifiInterface = self.getWifiInterface(interfaces: availableInterfaces)
let cellInterface = self.getCellInterface(interfaces: availableInterfaces)
var availableInterface : Connection = .unavailable
if let _ = cellInterface {
availableInterface = .cellular
}
if let _ = wifiInterface {
availableInterface = .wifi
}
self.lock.lock()
switch path.status {
case .requiresConnection, .satisfied:
self.connection = availableInterface
case .unsatisfied:
self.connection = .unavailable
@unknown default:
fatalError()
}
self.lock.unlock()

}
monitor.pathUpdateHandler = pathHandler
}
public func getConnection() -> Connection {
lock.lock()
defer {
lock.unlock()
}
return connection

}

func getCellInterface(interfaces: [NWInterface]) -> NWInterface? {
var foundInterface : NWInterface? = nil
interfaces.forEach { interface in
if interface.type == .cellular {
foundInterface = interface
}
}
return foundInterface
}
func getWifiInterface(interfaces: [NWInterface]) -> NWInterface? {
var foundInterface : NWInterface? = nil
interfaces.forEach { interface in
if interface.type == .wifi {
foundInterface = interface
}
}
return foundInterface
}
}



#else
import Reachability

public class NetworkMonitor: NetworkMonitorProtocol {
Expand All @@ -31,5 +102,5 @@ public class NetworkMonitor: NetworkMonitorProtocol {
}
}
}

#endif
#endif

0 comments on commit 31dfa63

Please sign in to comment.