我正在使用可达性,但其显示设备通过wifi或蜂窝数据连接。我只想知道设备是否连接到互联网。我只是使用了一些代码,它可以正常工作,但是如果设备未连接到互联网,则应用程序将变得免费。
struct hostent*hostinfo;
char*hostname="google.com";
hostinfo=gethostbyname(hostname);
if (hostinfo == NULL){
NSLog(@"-> no connection!\n");
}
答案 0 :(得分:0)
仅 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)
}
答案 1 :(得分:0)
使用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");
}