React to network status updates in SwiftUI
In this short post we'll look into how to easily manage network status updates in SwiftUI by using the NWPathMonitor as an async sequence. This method integrates seamlessly with your views for efficient updates.
import Network
struct ContentView: View {
@State private var isNetworkAvailable: Bool = false
var body: some View {
VStack {
if isNetworkAvailable {
Text("Network is Available")
} else {
Text("Network is Unavailable")
}
}
.task {
for await path in NWPathMonitor() {
isNetworkAvailable = path.status == .satisfied
}
}
}
}
Here we are enumerating over the async sequence of network path updates provided by NWPathMonitor()
. The view then displays the current network status based on this state. Additionally, the view’s task() modifier ensures that the async sequence is automatically canceled when the view disappears, safely cleaning up resources.