在开发wifi之前,有几个必须的步骤
1.添加Capability, Access WiFi Information
2.当前开发WiFi相关需要用户授权位置信息,你需要添加授权位置信息的代码,具体请查找CoreLocation相关的代码,当然不要忘记了在plist里要添加Privacy。
此时你可以获取到WiFi相关的数据了,不然会提示nehelper sent invalid result code [1] for Wi-Fi information request。
想要获取当前iphone设备连接的wifi的信息,下列代码返回的字典里包含了
+(NSDictionary *)currentWifiSSID
{
NSArray *ifs = (__bridge id)CNCopySupportedInterfaces();
id info = nil;
for (NSString *ifnam in ifs) {
info = (__bridge id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
if (info && [info count]) {
break;
}
}
NSDictionary *dctySSID = (NSDictionary *)info;
return dctySSID;
}
返回的NSDictionary格式
{
BSSID = "c:3a:fa:1:67:23";//设备的名字,类似于mac地址
SSID = ABC;//WiFi的名字
SSIDDATA = {length = 10, bytes = 0x53494e4f415353495354};
}
以下代码可以获取当前设备连接WiFi后所在局域网的ip地址
+ (nullable NSString*)vp_wifiIPAddress{
NSString *address = nil;
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
// retrieve the current interfaces - returns 0 on success
success = getifaddrs(&interfaces);
if (success == 0) {
// Loop through linked list of interfaces
temp_addr = interfaces;
while(temp_addr != NULL) {
if(temp_addr->ifa_addr->sa_family == AF_INET) {
// Check if interface is en0 which is the wifi connection on the iPhone
if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
// Get NSString from C String
address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
}
}
temp_addr = temp_addr->ifa_next;
}
}
// Free memory
freeifaddrs(interfaces);
return address;
}