// MARK: -
// MARK: - 判斷網(wǎng)絡(luò)類型
enum NetworkStatuses {
case NetworkStatusNone // 沒有網(wǎng)絡(luò)
case NetworkStatus2G // 2G
case NetworkStatus3G // 3G
case NetworkStatus4G // 4G
case NetworkStatusWIFI // WIFI
}
extension NetWorkTools {
/// 獲取網(wǎng)絡(luò)狀態(tài)
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")!) {
// 獲取到狀態(tài)欄碼
guard let networkType = child.value(forKey: "dataNetworkType") as? Int else { return nil }
switch (networkType) {
case 0: // 無網(wǎng)模式
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
}
}
}
// 返回網(wǎng)絡(luò)類型
return status;
}
}
需要注意的是
當(dāng)連接的wifi沒有網(wǎng)絡(luò)時(shí)候
會(huì)出現(xiàn)問題
所以還是推薦用網(wǎng)絡(luò)監(jiān)聽器來獲取網(wǎng)絡(luò)狀態(tài)
這個(gè)主要是用來判斷是2G/3G/4G網(wǎng)絡(luò)用的