NEHotspotConfigurationManager 加入已經(jīng)密碼的wifi網(wǎng)絡(luò)多用于物聯(lián)網(wǎng)捅彻。設(shè)備配置加入互聯(lián)網(wǎng)。
如圖勾選Hotpost
2.創(chuàng)建工程在Capabilities 中勾選Hotspot configuration
3.在Build Phases 中
4.在info.plist 中加入權(quán)限
以上三部環(huán)境配置完成了
下面開始使用
1.在使用的地方加入頭文件 #import <NetworkExtension/NEHotspotConfigurationManager.h>
- NEHotspotConfiguration* configuration = [[NEHotspotConfiguration alloc]initWithSSID:@"wifi名" passphrase:@"wifi密碼" isWEP:NO]; //加入有密碼的wifi
// NEHotspotConfiguration* configuration = [[NEHotspotConfiguration alloc]initWithSSID:@"wifi名"]; //加入沒有密碼的wifi
[[NEHotspotConfigurationManager sharedManager] applyConfiguration:configuration completionHandler:^(NSError * _Nullable error) {
if([[self currentIphoneConnectedWifiName]isEqualToString:@"NET"]) {
NSLog(@"加入網(wǎng)絡(luò)成功");
}
NSLog(@"%@",error);
}];
這個方法存在一個問題鞍陨,如果你加入一個不存在的WiFi沟饥,會彈出無法加入WiFi的彈框,但是本方法的回調(diào)error沒有值湾戳。在這里,我是通過判斷當(dāng)前wifi是否是我要加入的wifi來解決這個問題的广料。
后面是輔助的方法 查看手機當(dāng)前連接的wifi 先要導(dǎo)入頭文件
import <SystemConfiguration/CaptiveNetwork.h>
/** 獲取當(dāng)前手機連接到到Wi-Fi 的名字 */
-
(NSString *)currentIphoneConnectedWifiName{
NSString *wifiName = nil;
CFArrayRef wifiInterfaces = CNCopySupportedInterfaces();
if (!wifiInterfaces)return nil;
NSArray *interfaces = (__bridge NSArray *)wifiInterfaces;
for (NSString *interfaceName in interfaces){
CFDictionaryRef dictRef = CNCopyCurrentNetworkInfo((__bridge CFStringRef)(interfaceName));
if (dictRef){
NSDictionary *networkInfoDic = (__bridge NSDictionary *)dictRef;
wifiName = [networkInfoDic objectForKey:(__bridge NSString *)kCNNetworkInfoKeySSID];
CFRelease(dictRef);
}
}
CFRelease(wifiInterfaces);
return wifiName;
}