parent
f926a1fcbe
commit
b5b32892dc
@ -0,0 +1,59 @@ |
||||
// |
||||
// NetworkMonitor.swift |
||||
// LeStorage |
||||
// |
||||
// Created by Laurent Morvillier on 25/10/2024. |
||||
// |
||||
|
||||
import Network |
||||
import Foundation |
||||
|
||||
public class NetworkMonitor { |
||||
|
||||
public static let shared = NetworkMonitor() |
||||
private var monitor: NWPathMonitor |
||||
private var queue = DispatchQueue(label: "NetworkMonitor") |
||||
|
||||
public var isConnected: Bool { |
||||
get { |
||||
return status == .satisfied |
||||
} |
||||
} |
||||
|
||||
private(set) var status: NWPath.Status = .requiresConnection |
||||
|
||||
// Closure to be called when connection is established |
||||
var onConnectionEstablished: (() -> Void)? |
||||
|
||||
private init() { |
||||
monitor = NWPathMonitor() |
||||
self._startMonitoring() |
||||
} |
||||
|
||||
private func _startMonitoring() { |
||||
monitor.pathUpdateHandler = { [weak self] path in |
||||
guard let self = self else { return } |
||||
|
||||
// Update status |
||||
self.status = path.status |
||||
|
||||
// Print status for debugging |
||||
Logger.log("Network Status: \(path.status)") |
||||
|
||||
// Handle connection established |
||||
if path.status == .satisfied { |
||||
DispatchQueue.main.async { |
||||
self.onConnectionEstablished?() |
||||
} |
||||
} |
||||
|
||||
} |
||||
|
||||
monitor.start(queue: queue) |
||||
} |
||||
|
||||
func stopMonitoring() { |
||||
monitor.cancel() |
||||
} |
||||
|
||||
} |
||||
Loading…
Reference in new issue