You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
60 lines
1.4 KiB
60 lines
1.4 KiB
//
|
|
// 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: "lestorage.queue.network_monitor")
|
|
|
|
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?()
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
self._monitor.start(queue: self._queue)
|
|
}
|
|
|
|
func stopMonitoring() {
|
|
self._monitor.cancel()
|
|
}
|
|
|
|
}
|
|
|