Internet Connectivity in Swift

Updated 28 May 2021

Save

We often use networking in our projects. The very basic thing before we process any network-related task is to check connectivity. Here we will discuss Internet Connectivity in Swift

We can use the System Configuration Framework provided by Apple to detect the network reachability of the device.

System Configuration Framework can detect the internet connectivity, whether the device is connected through Wifi or any cellular network.

In addition, System Configuration Framework uses both IPv4 and IPv6.

Above all, let’s begin writing code for checking internet connectivity.

Internet Connectivity in Swift

Firstly we will start by creating a different class named NetworkManager.

After that, we will create a function called isConnectedToNetwork()  that returns the boolean value.

Explaining the Internet Connectivity in Swift

1. sockaddr_in() is an address type structure, there are different address types for different address families (such as struct sockaddr_in for IPv4, struct sockaddr_in6 for IPv6).
It contains various properties like:
sin_addr
sin_family
sin_len
sin_port
sin_zero

2. sizeofValue()  gives the size of the sockaddr_in() struct which has to be converted.

3. AF_INET is an Int32 that is converted for  sin_family

4. SCNetworkReachabilityCreateWithAddress creates a reachability reference to a certain network address.

5. After that, SCNetworkReachabilityFlags flags indicate the connectivity of a network address.

Note: Do not forget to import SystemConfiguration in the NetworkManager class

Usage

Above we defined the code for checking the internet connectivity, now we will see how to use them before making any network-related task.

For instance, you can call the NetworkManager class and access the isConnectedToNetwork function. In other words, isConnectedToNetwork will return the boolean value true if the internet is connected.

Similarly, it will return false if the device is not connected to the internet.

 

Use the above code in any view controller before doing any network-related task.

For more information, you can check the Apple documentation

Conclusion

I hope this blog will help you to implement the internet connectivity feature in your applications.

If you have any comments or questions, feel free to post them in the comment section below!

For other blogs Please click here

author
. . .

Leave a Comment

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


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home