NEW BOOK! Swift Gems: 100+ tips to take your Swift code to the next level. Learn more ...NEW BOOK! Swift Gems:100+ advanced Swift tips. 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.

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

Check out our new book!

Swift Gems

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

Swift Gems

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

  • 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
  • Practical Swift insights from years of development, applicable from iOS to server-side Swift