How to check internet availability using swift

Internet Availability

For every application, it is mandatory to ensure internet connection is available or not. So you can confirm the internet availability by using SCNetworkReachabilityAPI of  SystemConfiguration Framework which is by default offered in iOS, You do not have to utilize any third party library for that. Follow these steps to ensure internet availability:-

  • build a new Swift file with name InternetTest.
  • now you have to import the SystemConfiguration 
                import SystemConfiguration
  • To test your internet connection, write the following code to InternetTest file
import Foundation
import SystemConfiguration

public class ReachabilityTest {

 class func isConnectedToNetwork() -> Bool {

 var zeroAddress = sockaddr_in()
 zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
 zeroAddress.sin_family = sa_family_t(AF_INET)

 let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
 $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
 SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
 }
 }

 var flags = SCNetworkReachabilityFlags()
 if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
 return false
 }
 let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
 let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
 return (isReachable && !needsConnection)

 }

}
  • Then, you have to ensure that internet connection is available or not.
if ReachabilityTest.isConnectedToNetwork() {
 print("Internet connection available")
}
else{
 print("No internet connection available")
}

Posted

in

by

Comments

Leave a Reply

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