Check network status in SwiftU
• 2 min read
swiftui tips
This brief guide demonstrates a streamlined approach to handling network status changes in SwiftUI—by converting NWPathMonitor into an async sequence. The result is smooth integration with your views and efficient, real-time 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
}
}
}
}
In this code, we iterate through the async sequence of network path updates from NWPathMonitor(). The view renders the current network status according to this state. The task() modifier also handles cleanup automatically—it cancels the async sequence when the view disappears, ensuring proper resource management.