繁体   English   中英

检查是否有活跃的互联网可用ios

[英]Check if active internet available or not ios

我正在使用Reachability,但其显示设备通过wifi或蜂窝数据连接。 我只想要设备是否连接到互联网。 我只是使用了一些代码,它的工作正常,但如果设备没有连接到互联网,应用程序正在获得freez。

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

只有斯威夫特

你需要导入SystemConfiguration.CaptiveNetwork和bellow方法对我来说就像魅力一样

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)
}

使用NSURL检查互联网连接

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");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM