Check if iPhone has an active internet connection in SwiftUI

Hello.

I'm developing an app that completely relies on an internet connection and as such I want to know if there's a way to check if the iPhone has an active internet connection available because if it doesn't, I want to display a different view to the user stating that the app doesn't have an internet connection and so the app cannot be used.

This is a feature that exists in first party Apple apps like the App Store and also third party apps such as YouTube.

Does anyone know of an effective way to achieve this please?

Hi,

I use this code myself in my app:

class NetworkModel {
    
    static let shared = NetworkModel()
    
    private let monitor = NWPathMonitor()
    private var connected = true
    
    init() {
        monitor.pathUpdateHandler = { path in
            if path.status == .satisfied {
                self.connected = true
            } else {
                self.connected = false
            }
        }
        
        let queue = DispatchQueue(label: "Monitor")
        monitor.start(queue: queue)
    }
    
    /// Retrieves the current network state.
    ///
    /// - Returns: A boolean value indicating the network state (connected or not).
    func getNetworkState() -> Bool {
        return connected
    }
}

Downside is that the very first time it is accessed it is always false. So trigger it during launch so that the monitor can start watching and then it works perfect!

NWPathMonitor should get you what you need here as Jeroeneo has mentioned, however if you wanted to check if the device is completely offline too you could try sending a URLSessionDataTask and check for the immediate failure if the device is offline. This should allow your app to notify the user of the current status.

I wanna be clear there’s no such thing as an “active internet connection”, because the Internet is not one thing. The device might think that it has a path to the Internet, and that’ll be reported by NWPathMonitor, but that doesn’t mean that a network connection to a specific host will work. There are any number of reasons that might fail, many of which are completely out of your control (and the devices’s control, and the user’s control). For example, the host you’re trying to talk to might be offline.

This is a feature that exists in first party Apple apps like the App Store and also third party apps such as YouTube.

Those apps talk to a specific service and so they can make decisions based on their attempts to connect to that service. That is the approach I recommend. Specifically, if you’re using URLSession you can sets waitsForConnectivity, make your request, and then use the urlSession(_:taskIsWaitingForConnectivity:) delegate callback to drive your UI.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Check if iPhone has an active internet connection in SwiftUI
 
 
Q