NEW BOOK! SwiftUI Fundamentals: The essential guide to SwiftUI core concepts and APIs. Learn more ...NEW BOOK! SwiftUI Fundamentals:Master SwiftUI core concepts and APIs. Learn more...
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.

SwiftUI Fundamentals by Natalia Panferova book coverSwiftUI Fundamentals by Natalia Panferova book cover

Deepen your understanding of SwiftUI!$35

The essential guide to SwiftUI core concepts and APIs

SwiftUI Fundamentalsby Natalia Panferova

  • Explore the key APIs and design patterns that form the foundation of SwiftUI
  • Develop a deep, practical understanding of how SwiftUI works under the hood
  • Learn from a former Apple engineer who worked on widely used SwiftUI APIs

Deepen your understanding of SwiftUI!

The essential guide to SwiftUI core concepts and APIs

SwiftUI Fundamentals by Natalia Panferova book coverSwiftUI Fundamentals by Natalia Panferova book cover

SwiftUI Fundamentals

by Natalia Panferova

$35