0

I am using Reachability but its showing device is connected through wifi or cellular data. I just want if device is connected to internet or not. I just used some code, its working fine but app is getting freez if device not connected to internet.

struct hostent*hostinfo;
char*hostname="google.com";
hostinfo=gethostbyname(hostname);
if (hostinfo == NULL){
NSLog(@"-> no connection!\n");
}

2 Answers2

0

Only Swift

You need to import SystemConfiguration.CaptiveNetwork and bellow method works like charm for me

public class func isInternetAvailable() -> Bool {
    var zeroAddress        = sockaddr_in()
    zeroAddress.sin_len    = UInt8(MemoryLayout<sockaddr_in>.size)
    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)
}
Subhash Sharma
  • 745
  • 6
  • 24
0

Use NSURL for check internet connection

NSURL *url = [NSURL URLWithString:@"https://www.google.com/"];
if ([NSData dataWithContentsOfURL:url]) {
    NSLog(@"Device is connected to the Internet");
} else {
    NSLog(@"Device is not connected to the Internet");
}
arts
  • 118
  • 4