Created
November 28, 2024 13:33
-
-
Save mbernson/0bb57e7bca338fe25bda65ab8926d284 to your computer and use it in GitHub Desktop.
Monitor network connectivity in Swift using an async stream
This file contains hidden or 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
import Foundation | |
import Network | |
enum NetworkConnectivity { | |
case online | |
case offline | |
case unknown | |
} | |
let networkConnectivity = AsyncStream(NetworkConnectivity.self) { continuation in | |
let queue = DispatchQueue(label: "NetworkConnectivityStream") | |
let pathMonitor = NWPathMonitor() | |
pathMonitor.pathUpdateHandler = { path in | |
continuation.yield(path.mapToNetworkConnectivity()) | |
} | |
continuation.onTermination = { reason in | |
pathMonitor.cancel() | |
} | |
continuation.yield(pathMonitor.currentPath.mapToNetworkConnectivity()) | |
pathMonitor.start(queue: queue) | |
} | |
private extension NWPath { | |
func mapToNetworkConnectivity() -> NetworkConnectivity { | |
switch status { | |
case .satisfied: | |
.online | |
case .unsatisfied: | |
.offline | |
case .requiresConnection: | |
.unknown | |
@unknown default: | |
.unknown | |
} | |
} | |
} | |
for await status in networkConnectivity { | |
print("Status: \(status)") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment