Quick Tip Icon
Quick Tip

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.

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Level up your Swift skills!$35

100+ tips to take your Swift code to the next level

Swift Gemsby Natalia Panferova

  • Advanced Swift techniques for experienced developers bypassing basic tutorials
  • Curated, actionable tips ready for immediate integration into any Swift project
  • Strategies to improve code quality, structure, and performance across all platforms

Level up your Swift skills!

100+ tips to take your Swift code to the next level

Swift Gems by Natalia Panferova book coverSwift Gems by Natalia Panferova book cover

Swift Gems

by Natalia Panferova

$35