SPB Git

Repository Public

NetworkMonitor.swift 2.7 KB 74 lines swift

1//2//  SP Chat iOS3//  File: SPChat-iOS/Core/Networking/NetworkMonitor.swift4//  Description: Reachability (NWPathMonitor) published to the UI, with an async "wait until online".5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//910import Foundation11import Network12import Observation13import os1415@MainActor16@Observable17final class NetworkMonitor {18    private(set) var isOnline = true19    private(set) var isExpensive = false20    /// Incremented each time connectivity comes back; views and the sync engine observe it.21    private(set) var reconnections = 02223    @ObservationIgnored private let monitor = NWPathMonitor()24    /// Tests drive connectivity themselves; the real path monitor is then ignored.25    @ObservationIgnored private var isSimulated = false26    @ObservationIgnored private var waiters: [CheckedContinuation<Void, Never>] = []27    /// Lock-protected mirror readable from any isolation domain (the HTTP actor words its errors with it).28    @ObservationIgnored nonisolated let offlineFlag = OSAllocatedUnfairLock(initialState: false)2930    init() {31        monitor.pathUpdateHandler = { [weak self] path in32            let online = path.status == .satisfied33            let expensive = path.isExpensive34            Task { @MainActor [weak self] in35                guard let self, !self.isSimulated else { return }36                self.update(online: online, expensive: expensive)37            }38        }39        monitor.start(queue: DispatchQueue(label: "ai.spboucher.spchat.network"))40    }4142    private func update(online: Bool, expensive: Bool) {43        let was = isOnline44        isOnline = online; isExpensive = expensive45        offlineFlag.withLock { $0 = !online }46        if online && !was {47            reconnections += 148            let w = waiters; waiters.removeAll()49            w.forEach { $0.resume() }50        }51    }5253    /// Suspends until the device has a network path again (returns at once when online or when the task is cancelled).54    func waitUntilOnline() async {55        if isOnline { return }56        await withTaskCancellationHandler {57            await withCheckedContinuation { (c: CheckedContinuation<Void, Never>) in58                if isOnline || Task.isCancelled { c.resume() } else { waiters.append(c) }59            }60        } onCancel: {61            Task { @MainActor [weak self] in62                guard let self else { return }63                let w = self.waiters; self.waiters.removeAll()64                w.forEach { $0.resume() }65            }66        }67    }6869    #if DEBUG70    /// Test hook: simulates losing and regaining the network.71    func simulate(online: Bool) { isSimulated = true; update(online: online, expensive: false) }72    #endif73}74
Files main
Menu

Theme