iOS 14及以上:
- 需导入CoreLocation库
- 需获取到精确定位权限
具体不详细展开,网上资料非常多,贴关键代码.
@property (nonatomic, strong) CLLocationManager *locationManager; // 定位管理器
/// ios 14 自动请求临时开启一次精确定位权限
- (void)autoRequestTemporaryFullAccuracyAuthorization {
if (@available(iOS 14.0, *)) {
BOOL isFullAccuracy = self.locationManager.accuracyAuthorization == CLAccuracyAuthorizationFullAccuracy;
if (isFullAccuracy) {
NSLog(@"当前为精确定位状态,不需要申请临时开启一次精确位置权限.");
} else {
NSLog(@"当前为模糊定位状态,需要向用户申请临时开启一次精确位置权限.");
// 向用户申请临时开启一次精确位置权限
[self.locationManager requestTemporaryFullAccuracyAuthorizationWithPurposeKey:@"WantsToGetWiFiSSID"];
}
} else {
}
}
- (CLLocationManager *)locationManager {
if (_locationManager == nil) {
_locationManager = [[CLLocationManager alloc]init];
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
_locationManager.distanceFilter = 0.1;
}
return _locationManager;
}
[NEHotspotNetwork fetchCurrentWithCompletionHandler:^(NEHotspotNetwork * _Nullable currentNetwork) {
if (currentNetwork != nil && currentNetwork.SSID != nil) {
NSLog(@"当前Wifi的SSID--%@",currentNetwork.SSID);
} else {
}
}];
iOS 9 - iOS 13:
- 由于iOS12之后需要根据定位才能获取Wifi信息,现有的项目基本从iOS 10或11起步了,所以直接按照iOS12的标准来做,也是需要得到定位权限后再进行获取.
- 网上很多技术贴的获取方法, 在连接普通路由器时没有问题,但在连接手机开启的热点时,获取的SSID是一个空字符串。
- 下面是连接热点和普通路由器都正常获取的代码(resultBlock可忽略并自行处理结果回调)
/// 获取SSID
- (void)getSSID {
if (@available(iOS 14.0, *)) {
[NEHotspotNetwork fetchCurrentWithCompletionHandler:^(NEHotspotNetwork * _Nullable currentNetwork) {
if (currentNetwork && currentNetwork.SSID && self.resultBlock) {
self.resultBlock(@{@"wifiSsid":currentNetwork.SSID});
} else {
self.resultBlock(@{@"wifiSsid": @"",
@"error":@"Please check your wifi connect status"});
}
}];
return;
}
// iOS 14以下获取wifi名字
NSString * wifiName = @"";
CFArrayRef wifiInterfaces = CNCopySupportedInterfaces();
if (wifiInterfaces) {
NSArray *interfaces = (__bridge NSArray *)wifiInterfaces;
for (NSString *interfaceName in interfaces) {
CFDictionaryRef dictRef = CNCopyCurrentNetworkInfo((__bridge CFStringRef)(interfaceName));
if (dictRef) {
NSDictionary *networkInfo = (__bridge NSDictionary *)dictRef;
NSLog(@"网络信息-->%@",networkInfo);
wifiName = [networkInfo objectForKey:(__bridge NSString *)kCNNetworkInfoKeySSID];
CFRelease(dictRef);
break;
}
}
}
CFRelease(wifiInterfaces);
if (self.resultBlock) {
self.resultBlock(@{@"wifiSsid": wifiName});
}
}