Swift
import SystemConfiguration
/// Class helps to code reuse in handling internet network connections.
class NetworkHelper {
/**
Verify if the device is connected to internet network.
- returns: true if is connected to any internet network, false if is not
connected to any internet network.
*/
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}
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)
}
}
if NetworkHelper.isConnectedToNetwork() {
// Is connected to network
}
Objective-C:
we can check network connectivity within few lines of code as:
-(BOOL)isConntectedToNetwork
{
Reachability *networkReachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
if (networkStatus == NotReachable)
{
NSLog(@"There IS NO internet connection");
return false;
} else
{
NSLog(@"There IS internet connection");
return true;
}
}