【问题标题】:Check if active internet available or not ios检查是否有可用的互联网 ios
【发布时间】:2019-09-30 11:31:24
【问题描述】:

我正在使用 Reachability,但它的显示设备是通过 wifi 或蜂窝数据连接的。我只想要设备是否连接到互联网。我刚刚使用了一些代码,它工作正常,但如果设备未连接到互联网,应用程序就会冻结。

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

【问题讨论】:

标签: ios objective-c


【解决方案1】:

Swift

你需要导入SystemConfiguration.CaptiveNetwork,下面的方法对我来说就像魅力一样

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

【讨论】:

  • 我正在寻找目标c
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多