With iOS 12, Apple has introduced Network, a framework that includes the NWPathMonitor class. NWPathMonitor gives us the means to monitor changes of state in the internet connection (so it is no longer necessary to use the Reachability class, in applications that support iOS 12 onwards). Therefore, we can set aside the Reachability library, and detect the state of the network with NWPathMonitor.

To use this new way to check the status of the internet connection, we first need to create an instance of NWPathMonitor:

We can also instantiate the NWPathMonitor class indicating a particular type of network that we want to check. For example, to check WiFi connections:

NWPathMonitor can check different types of interfaces:

  • cellular. For 3G / 4G connections.
  • loopback. For localhost.
  • other. For virtual networks or unknown network types.
  • wifi. For WiFi connections.
  • wiredEthernet. If the device is connected to the internet by cable.

Detection of changes in the state of the internet connection are made through the pathUpdateHandler property:

path is of NWPath type and, according to Apple documentation, status can be:

  • unsatisfied. The connection (path) cannot be used.
  • satisfied. The connection (path) has been established and allows data to be sent.
  • requiresConnection. The connection (path) is not currently available, but if a new connection is established it can be activated.

For more information on the possibilities of NWPath we can access the Apple documentation.
Finally, in order to start receiving information about changes in the state of the internet connection, we need to call the start () method. The start () method needs a queue to do this job:

Once we no longer need to know the changes in the state of the internet connection, we will call the cancel () method.

Code example

For example, suppose we want to know at all times the status of the internet connection throughout the application. For this we can use a class of type Singleton:

Where ConnectionType is an enum that contains the specific cases of connectivity for our app. For example:

To use this Singleton type class:


0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Follow on Feedly
shares