iOS
macOS
Internet Connection
Programming
Network Troubleshooting

How can I check for an active Internet connection on iOS or macOS?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Checking for an active internet connection is a critical functionality in many iOS and macOS applications. Ensuring that your device has a viable internet connection can influence how your application behaves, what features are available, and how data is managed. In this article, we'll explore multiple methods and tools provided by Apple and other sources to check internet connectivity effectively on iOS and macOS platforms.

Understanding Network Connectivity on iOS and macOS

Apple provides specific frameworks to help developers manage and monitor network connections. The primary framework used for networking tasks on iOS and macOS is Network.framework. Before this, the Reachability class was widely used, particularly for older applications still running on Objective-C or earlier Swift versions.

Using the Network Framework

Introduced in iOS 12 and macOS 10.14, Network.framework provides a modern approach to monitor network connections and changes in network status.

1. Monitor Connectivity

Here's how you can use Network.framework to check for an internet connection:

swift
1import Network
2
3class ConnectivityMonitor {
4    private var monitor: NWPathMonitor?
5    private var isMonitoring = false
6
7    func startMonitoring() {
8        guard !isMonitoring else { return }
9
10        monitor = NWPathMonitor()
11        let queue = DispatchQueue.global(qos: .background)
12        monitor?.start(queue: queue)
13
14        monitor?.pathUpdateHandler = { path in
15            if path.status == .satisfied {
16                print("We're connected!")
17            } else {
18                print("No connection.")
19            }
20            print(path.isExpensive ? "The connection is cellular." : "The connection is WiFi.")
21        }
22
23        isMonitoring = true
24    }
25
26    func stopMonitoring() {
27        guard isMonitoring, let monitor = monitor else { return }
28        
29        monitor.cancel()
30        self.monitor = nil
31        isMonitoring = false
32    }
33}

This snippet sets up a network path monitor, which reports any changes to the device’s network conditions including becoming connected, losing connection, or switching type of connection (like from Wi-Fi to cellular).

2. Checking Internet Access

To specifically check for internet access, you can use the NWPathMonitor with a specific configuration:

swift
1let monitor = NWPathMonitor(requiredInterfaceType: .wifi)
2let internetMonitor = NWPathMonitor(requiredInterfaceType: .internet)
3
4monitor.pathUpdateHandler = { path in
5    if path.status == .satisfied {
6        // Device has internet access
7    } else {
8        // Device does not have internet access
9    }
10}
11monitor.start(queue: DispatchQueue.global(qos: .background))

Understanding Reachability

For legacy projects or simpler network checks, you might still encounter or choose to use the Reachability class. This class provides a way to determine internet reachability status. Here's an example using Reachability.swift, a popular Swift version of the original Reachability objective-C implementation:

swift
1import Reachability
2
3let reachability = try? Reachability()
4
5NotificationCenter.default.addObserver(self,
6                                       selector: #selector(networkStatusChanged(_:)),
7                                       name: .reachabilityChanged,
8                                       object: reachability)
9
10try? reachability?.startNotifier()
11
12@objc func networkStatusChanged(_ notification: Notification) {
13    if let reachability = notification.object as? Reachability {
14        switch reachability.connection {
15        case .wifi:
16            print("Reachability: WiFi")
17        case .cellular:
18            print("Reachability: Cellular")
19        case .unavailable:
20            print("Reachability: No Connection")
21        default:
22            break
23        }
24    }
25}

Summary of Key Points

Here's a table summarizing the methods discussed:

MethodFrameworkiOS VersionmacOS VersionReal-time UpdatesAdditional Info
NWPathMonitorNetworkiOS 12+macOS 10.14+YesModern, recommended method
ReachabilityExternal libraryiOS 2+macOS N/AYesLegacy method, not built into Apple's frameworks

Additional Considerations

  • Handling Connectivity Changes: Always design your app to react gracefully to changes in network status. This can mean pausing downloads, saving user progress, or caching important data.
  • User Notifications: Consider informing users of connectivity issues, especially if network access is critical for your app's functionality.
  • Testing: Simulate different network environments (like offline, slow connectivity, cellular, Wi-Fi) during your app's testing phases.

By integrating robust internet connection checks and handling network changes efficiently, you can enhance user experience and maintain smooth operation across iOS and macOS apps.


Course illustration
Course illustration

All Rights Reserved.