iOS下Wi-Fi開發需要添加依賴庫SystemConfiguration.framework,在需要使用Wi-Fi信息的控制器下引入頭文件#import <SystemConfiguration/CaptiveNetwork.h>
1,Wi-Fi熱點獲取
+(NSString *) currentWifiSSID { #if TARGET_OS_SIMULATOR return @"(simulator)"; #else 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; NSString *ssid = [dctySSID objectForKey:@"SSID"] ; return ssid; #endif }
2,取得本機Wi-Fi的IP地址
#include <arpa/inet.h> #include <netdb.h> #include <net/if.h> #include <ifaddrs.h> #import <dlfcn.h> +(NSString *) localWiFiIPAddress { BOOL success; struct ifaddrs * addrs; const struct ifaddrs * cursor; success = getifaddrs(&addrs) == 0; if (success) { cursor = addrs; while (cursor != NULL) { // the second test keeps from picking up the loopback address if (cursor->ifa_addr->sa_family == AF_INET && (cursor->ifa_flags & IFF_LOOPBACK) == 0) { NSString *name = [NSString stringWithUTF8String:cursor->ifa_name]; if ([name isEqualToString:@"en0"]) // Wi-Fi adapter return [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)]; } cursor = cursor->ifa_next; } freeifaddrs(addrs); } return nil; }
3,獲取當前Wi-Fi的名稱
- (void)GetWifiName{ NSString *wifiName = @"Not Found"; CFArrayRef myArray = CNCopySupportedInterfaces(); if (myArray != nil) { CFDictionaryRef myDict =CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0)); if (myDict != nil) { NSDictionary *dict = (NSDictionary*)CFBridgingRelease(myDict); wifiName = [dict valueForKey:@"SSID"]; } NSLog(@"wifiName:%@", wifiName); }
注意:需要真機才能測試!模擬器下返回空。