Imagine you’re using a mobile app to browse your favourite news website or stream music, and suddenly you lose internet connectivity. So today in this blog we will learn how we can handle these cases on our Application.
Why Check for Internet Availability?
In Swift app development, checking for internet availability is vital for delivering a seamless user experience and handling network-related errors. Without handling this properly, the app might crash or display confusing error messages, affecting your app’s user experience.
By adding checks for internet availability in your Application, you can effectively prevent such scenarios while maintaining the best user experience and integrity of your application.
How to check the internet Connectivity?
In Swift programming, there are a lot of ways you can check the internet connectivity of the device. In this blog, we will learn to check the internet connectivity with the SCNetworkReachability API of SystemConfiguration Framework.
To integrate the SystemConfiguration Framework, you can follow the below steps to check the internet connectivity.
Step 1. Import the SystemConfiguration Framework in your Swift file.
1 2 |
import SystemConfiguration import UIKit |
Step 2. Define a Function to Check Internet Connectivity using SCNetworkReachability
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
func isConnectedToNetwork() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { SCNetworkReachabilityCreateWithAddress(nil, $0) } }) else { return false } var flags: SCNetworkReachabilityFlags = [] if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) { return false } let isReachable = flags.contains(.reachable) let needsConnection = flags.contains(.connectionRequired) return (isReachable && !needsConnection) } |
Step 3. Once the function is defined, all you need to do is call the function whenever you need to check the connectivity.
1 2 3 4 5 |
if isConnectedToNetwork() { print("Internet is available") } else { print("Internet is not available") } |
Conclusion
With this, we have learned about how we can check internet availability in Swift and how we can effectively use these in our daily programming practice.
You can continue your learning journey with more interesting topics and technologies with the Mobikul Blog. You can also check our Flutter Development Services.