iOS 如何检测当前连接的 WIFI 频段是 2.4G 还是 5G?
时间: 2024-04-08 12:33:57 浏览: 15
在 iOS 中,可以使用 `CNCopyCurrentNetworkInfo` 函数来获取当前连接的 Wi-Fi 信息,包括频段信息。以下是一个示例代码:
```swift
import SystemConfiguration.CaptiveNetwork
func getCurrentWiFiInfo() -> [String: Any]? {
var currentWiFiInfo: [String: Any]?
if let interfaces = CNCopySupportedInterfaces() as NSArray? {
for interface in interfaces {
if let interfaceInfo = CNCopyCurrentNetworkInfo(interface as! CFString) as NSDictionary? {
currentWiFiInfo = interfaceInfo as? [String: Any]
break
}
}
}
return currentWiFiInfo
}
func getCurrentWiFiFrequency() -> String? {
guard let currentWiFiInfo = getCurrentWiFiInfo(),
let ssid = currentWiFiInfo["SSID"] as? String,
let bssid = currentWiFiInfo["BSSID"] as? String else {
return nil
}
let frequencyRange2_4G = "2.4 GHz"
let frequencyRange5G = "5 GHz"
// 判断 BSSID 是否以特定的前缀开头来确定频段
if bssid.hasPrefix("a0:") || bssid.hasPrefix("a2:") || bssid.hasPrefix("a4:") ||
bssid.hasPrefix("a6:") || bssid.hasPrefix("a8:") || bssid.hasPrefix("aa:") ||
bssid.hasPrefix("ac:") || bssid.hasPrefix("ae:") || bssid.hasPrefix("b0:") ||
bssid.hasPrefix("b2:") || bssid.hasPrefix("b4:") || bssid.hasPrefix("b6:") ||
bssid.hasPrefix("b8:") || bssid.hasPrefix("ba:") || bssid.hasPrefix("bc:") ||
bssid.hasPrefix("be:") {
return frequencyRange5G
} else {
return frequencyRange2_4G
}
}
// 获取当前连接的 Wi-Fi 频段
if let currentFrequency = getCurrentWiFiFrequency() {
print("当前连接的 Wi-Fi 频段是 \(currentFrequency)")
} else {
print("无法获取当前连接的 Wi-Fi 频段")
}
```
以上代码中,`getCurrentWiFiInfo` 函数用于获取当前连接的 Wi-Fi 信息,而 `getCurrentWiFiFrequency` 函数则根据 BSSID 的前缀判断频段是 2.4GHz 还是 5GHz。