Verify if is connected to network
suggest changeSwift
import SystemConfiguration
/// Helps reuse code that checks internet connections. Swift 2 (`sizeofValue`, `withUnsafePointer`).
class NetworkHelper {
/**
Verify whether the device is connected to an internet network.
- returns: true if connected to any internet network, false if not.
*/
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 in a few lines. This uses the third-party Reachability class, which is not part of UIKit:
-(BOOL)isConnectedToNetwork
{
Reachability *networkReachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
if (networkStatus == NotReachable)
{
NSLog(@"There IS NO internet connection");
return NO;
} else
{
NSLog(@"There IS internet connection");
return YES;
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents