WiFi配网1 - 获取本机连接的WiFi名称

项目暂时告一段落,整理下大概功能及遇到的问题。

需求:给WiFi对讲机配网
大概流程:1.获取本机连接的WiFi名称 2.将WiFi名称和密码发送给设备

1.1 开启WiFi功能权限

如下图,点击+Capability,选择添加 Access WiFi Information


开启WiFi功能.png

1.2 获取定位权限

iOS13后需要开启定位权限后,才能获取WiFi名称,记得在info.plist添加相应描述:
Privacy - Location Always and When In Use Usage Description
Privacy - Location Always Usage Description
Privacy - Location When In Use Usage Description

- (void)openUserLocationAuth {
    if (![self getUserLocationAuth]) {
        CLLocationManager *locationManager = [[CLLocationManager alloc]init];
        [locationManager requestWhenInUseAuthorization];
    }
}

- (BOOL)getUserLocationAuth {
    BOOL result = NO;
    switch ([CLLocationManager authorizationStatus]) {
        case kCLAuthorizationStatusNotDetermined:
            break;
        case kCLAuthorizationStatusRestricted:
            break;
        case kCLAuthorizationStatusDenied:
            break;
        case kCLAuthorizationStatusAuthorizedAlways:
            result = YES;
            break;
        case kCLAuthorizationStatusAuthorizedWhenInUse:
            result = YES;
            break;
            
        default:
            break;
    }
    return result;
}

1.3 获取WiFi名称

#import

- (NSString *)getSSID {
    NSDictionary *netInfo = [self fetchSSIDInfo];
    NSString *ssidStr = [netInfo objectForKey:@"SSID"];
    return ssidStr;
}
/**
 *  获取SSID信息
 *
 *  @return id
 */
- (id)fetchSSIDInfo {
    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
    id info = nil;
    for (NSString *ifnam in ifs) {
        info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        
        if (info && [info count]) {
            break;
        }
    }
    return info;
}

注:当前方法仅能获取手机连接的WiFi,如果想获得扫描的WiFi列表,参考如下:
获得WiFi列表

你可能感兴趣的:(WiFi配网1 - 获取本机连接的WiFi名称)