1. 程式人生 > >macOS 開發 - 使用 CNCopySupportedInterfaces 獲取 WiFi ssid

macOS 開發 - 使用 CNCopySupportedInterfaces 獲取 WiFi ssid

文章目錄


SSID 全稱 Service Set IDentifier


CNCopySupportedInterfaces 核心程式碼

- (void)testWifiInfo{

    NSDictionary *currentWifiInfo = nil;

    // 獲取當前的interface 陣列
    // CNCopyCurrentNetworkInfo()
    CFArrayRef currentInterfaces = CNCopySupportedInterfaces();

    if (!currentInterfaces) {
        return ;
    }

    NSArray *interfaces = (__bridge NSArray *)(currentInterfaces);

    //無論是否開啟WiFi,都會顯示 WiFi 網絡卡 bsd name;無論是否連線有線,都不顯示有線網絡卡
    NSLog(@"interfaces : %@",interfaces);
    /*
    interfaces : (
    en1
    )
    */


    if (interfaces.count >0) {
        for (NSString *interfaceName in interfaces) {


            // 轉換型別,不改變引用計數
//            CFDictionaryRef dictRef = CNCopyCurrentNetworkInfo((__bridge CFStringRef)interfaceName);
//
//            if (dictRef) {
//                NSDictionary *networkInfo = (__bridge NSDictionary *)dictRef;
//
//                NSString *SSID = [networkInfo objectForKey:(__bridge NSString *)kCNNetworkInfoKeySSID];
//
//                NSString *BSSID = [networkInfoobjectForKey:(__bridge NSString *)kCNNetworkInfoKeyBSSID];
//
//                NSData *SSIDDATA = [networkInfoobjectForKey:(__bridge NSData *)kCNNetworkInfoKeySSIDData];
//
//                currentWifiInfo = @{@"SSID":SSID,
//                                    @"BSSID":BSSID,
//                                    @"SSIDDATA":SSIDDATA};

            }
        }

//    NSLog(@"currentWifiInfo = %@",currentWifiInfo);

}

CNCopyCurrentNetworkInfo 在 iOS 可用,在 Mac 不可用

當在 Mac 上使用 CNCopyCurrentNetworkInfo 時,會提示:
'CNCopyCurrentNetworkInfo' is unavailable: not available on macOS


前往檢視 CNCopyCurrentNetworkInfo 定義時,會發現:

CFDictionaryRef __nullable
CNCopyCurrentNetworkInfo (CFStringRef interfaceName) __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_4_1);

注意這裡標記了 __MAC_NA