针对不同的系统,需要作兼容
iOS 13 之后的系统,需要获取定位权限才能开启获取 SSID
<key>NSLocationAlwaysUsageDescription</key>
<string></string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string></string>
<key>NSLocationUsageDescription</key>
<string></string>
<key>NSLocationWhenInUseUsageDescription</key>
<string></string>
对应权限截图为:
Capability 中还要开启对应权限
拿到 Access WiFi Information
代码
class WiFiSSIDHelper: NSObject {
override init() {
super.init()
}
// 对于 iOS 13 以上系统需要增加请求定位权限的判断,否则无法获得 SSID
// 参考链接:https://juejin.im/post/6844903909564088327
func getWifiSSID() -> String? {
if #available(iOS 13.0, *) {
//用户明确拒绝,可以弹窗提示用户到设置中手动打开权限
if CLLocationManager.authorizationStatus() == .denied {
print("User has explicitly denied authorization for this application, or location services are disabled in Settings.")
//使用下面接口可以打开当前应用的设置页面
//[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
return nil
}
let cllocation = CLLocationManager()
if !CLLocationManager.locationServicesEnabled() || CLLocationManager.authorizationStatus() == .notDetermined {
//弹框提示用户是否开启位置权限
cllocation.requestWhenInUseAuthorization()
usleep(500)
//递归等待用户选选择
return getWifiSSID()
}
}
var wifiName: String? = nil
let wifiInterfaces = CNCopySupportedInterfaces()
if wifiInterfaces == nil {
return nil
}
let interfaces = wifiInterfaces as? [AnyHashable]
for interfaceName in interfaces ?? [] {
guard let interfaceName = interfaceName as? String else {
continue
}
let dictRef = CNCopyCurrentNetworkInfo(interfaceName as CFString)
if let dictRef = dictRef {
let networkInfo = dictRef as? [AnyHashable : Any]
print("network info -> \(networkInfo ?? [:])")
wifiName = networkInfo?[(kCNNetworkInfoKeySSID as String)] as? String
}
}
return wifiName
}
}