How to check Internet Availability in Swift
In this article, we will explore how to check internet availability in Swift using the Network
framework, introduced in iOS 12 and macOS 10.14.
The Network
framework provides a set of APIs that allow developers to monitor network connectivity and make informed decisions based on the network status.
Step 1: Import the Network
Framework.
To start using the Network framework in your project, you need to import it first. Add the following line at the top of your Swift file:
import Network
Step 2: Create a Network Monitor.
To check internet availability, we need to create a network monitor instance. This monitor will notify us whenever the network connection status changes. Add the following code to create a network monitor:
let monitor = NWPathMonitor()
Step 3: Define a Handler for Network Changes.
Next, we need to define a handler that will be called whenever the network connection changes. This handler will allow us to take appropriate action based on the current network status. Add the following code to set up the network change handler:
monitor.pathUpdateHandler = { path in
if path.status == .satisfied {
print("Internet connection is available.")
// Perform actions when internet is available
} else {
print("Internet connection is not available.")
// Perform actions when internet is not available
}
}
Step 4: Start the Network Monitor.
After setting up the handler, we can start the network monitor to begin observing the network status.
Creating a separate dispatch queue for network monitoring is crucial to prevent blocking the main queue and maintain a responsive user interface. By offloading network monitoring tasks to a dedicated queue, developers can ensure smooth user interactions while continuously monitoring the network status in the background.
Add the following code to start the network monitor:
let queue = DispatchQueue(label: "NetworkMonitor")
monitor.start(queue: queue)
The Network
framework provides the NWPath
class, which represents the current state of the network connection and provides valuable information about its availability and characteristics.
The status
property
The status
property of NWPath
is of type NWPath.Status
, which is an enumeration with the following possible values:
.satisfied
: Indicates that the network connection is available and meets the requirements of the application..unsatisfied
: Denotes that the network connection is unavailable or does not meet the requirements of the application..requiresConnection
: Specifies that the network connection is necessary but is currently not available. This status is typically seen when the device is in Airplane Mode.
By accessing the status
property, you can easily determine the current network status and tailor the app's behavior accordingly.
The isConstrained
property
The isConstrained
property of NWPath
helps identify whether the network connection is constrained or limited in some way. A constrained network connection typically implies restricted bandwidth, high latency, or other limitations that may impact the performance of network-dependent operations.
You can use the isConstrained
property to dynamically adjust the behavior of the app to optimize the user experience based on the network constraints. For example, you may choose to reduce the quality of downloaded media or limit the amount of data being transferred in constrained network scenarios.
The isExpensive
property
The isExpensive
property of NWPath
allows you to determine whether the network connection is considered expensive in terms of cost or data usage. This is particularly relevant for applications that rely on consuming a significant amount of data or for users who have limited data plans.
By checking the isExpensive
property, you can provide appropriate warnings or allow users to customize the app's behavior to optimize their data consumption and avoid unexpected charges.
The usesInterfaceType(_:)
method
The usesInterfaceType
method of NWPath
accepts an NWInterface.InterfaceType
parameter and returns a Boolean value. It allows us to check whether the network connection uses a specific interface type.
By calling the usesInterfaceType(_:)
method you can determine whether the device is connected via Wi-Fi, cellular, wired Ethernet, or other network interfaces.
The given code sample demonstrates how to check if the device is connected via Wi-Fi or cellular network:
let usesWiFi = path.usesInterfaceType(.wifi)
let usesCellular = path.usesInterfaceType(.cellular)
By using the provided APIs, you can easily monitor the network status and take appropriate actions within your iOS applications. Whether it’s displaying a user-friendly message or adjusting the functionality based on the network availability, the Network framework empowers you to create a better user experience.