// MARK: -
// MARK: - 判断网络类型
enum NetworkStatuses {
case NetworkStatusNone // 没有网络
case NetworkStatus2G // 2G
case NetworkStatus3G // 3G
case NetworkStatus4G // 4G
case NetworkStatusWIFI // WIFI
}
extension NetWorkTools {
/// 获取网络状态
class func getNetworkStates() -> NetworkStatuses? {
guard let object1 = UIApplication.shared.value(forKey: "statusBar") as? NSObject else { return nil }
guard let object2 = object1.value(forKey: "foregroundView") as? UIView else { return nil }
let subviews = object2.subviews
var status = NetworkStatuses.NetworkStatusNone
for child in subviews {
if child.isKind(of: NSClassFromString("UIStatusBarDataNetworkItemView")!) {
// 获取到状态栏码
guard let networkType = child.value(forKey: "dataNetworkType") as? Int else { return nil }
switch (networkType) {
case 0: // 无网模式
status = NetworkStatuses.NetworkStatusNone;
case 1: // 2G模式
status = NetworkStatuses.NetworkStatus2G;
case 2: // 3G模式
status = NetworkStatuses.NetworkStatus3G;
case 3: // 4G模式
status = NetworkStatuses.NetworkStatus4G;
case 5: // WIFI模式
status = NetworkStatuses.NetworkStatusWIFI;
default:
break
}
}
}
// 返回网络类型
return status;
}
}
需要注意的是
当连接的wifi没有网络时候
会出现问题
所以还是推荐用网络监听器来获取网络状态
这个主要是用来判断是2G/3G/4G网络用的
网友评论