1. 程式人生 > >iphone ipad 獲取wifi資訊 BSSID SSID

iphone ipad 獲取wifi資訊 BSSID SSID

首先,app如果要上app store是沒有辦法獲取wifi列表的~ 

這些WIFI掃描軟體使用了蘋果的私有函式apple80211.framework 

儘管不能合法(指能通過App Store的稽核)的獲取WIFI列表, 不過我們還是可以獲取到當前Wifi連線的資訊,比如SSID. BSSID
SSID全稱Service Set IDentifier, 即Wifi網路的公開名稱. 

BSSID 是指站點的 MAC 地址.

蘋果在IOS v4.1+版本上提供了公開的方法來獲取該資訊. 

注意記得要在build phases中新增庫SystemConfiguration.framework

#import <SystemConfiguration/CaptiveNetwork.h>  
  
- (id)fetchSSIDInfo  
{  
    NSArray *ifs = (id)CNCopySupportedInterfaces();  
    NSLog(@"%s: Supported interfaces: %@", __func__, ifs);  
    id info = nil;  
    for (NSString *ifnam in ifs) {  
        info = (id)CNCopyCurrentNetworkInfo((CFStringRef)ifnam);  
        NSLog(@"%s: %@ => %@", __func__, ifnam, info);  
        if (info && [info count]) {  
            break;  
        }  
        [info release];  
    }  
    [ifs release];  
    return [info autorelease];  
} 


ARC版本

#import <SystemConfiguration/CaptiveNetwork.h>
- (id)fetchSSIDInfo {  
     NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();  
     NSLog(@"Supported interfaces: %@", ifs);  
     id info = nil;  
     for (NSString *ifnam in ifs) {  
         info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);  
         NSLog(@"%@ => %@", ifnam, info);  //單個數據info[@"SSID"]; info[@"BSSID"];
         if (info && [info count]) { break; }  
     }  
     return info;  
}

輸出結果
2013-09-05 10:32:00.655 wifiTest[3534:707] -[wifiTestAppDelegate fetchSSIDInfo]: Supported interfaces: (  
    en0  
)  
2013-09-05 10:32:00.661 wifiTest [3534:707] -[wifiTestAppDelegate fetchSSIDInfo]: en0 => {  
    BSSID = "0:4:c3:a1:2b:22";  
    SSID = wifiname;  
    SSIDDATA = <01234567 76543210>;  
}

BSSID 正確格式是 00:04:c3:a1:2b:22 但是輸出以後卻是0:4:c3:a1:2b:22 少了頭0,可用一下方法補0

- (NSString *)standardFormateMAC:(NSString *)MAC {
    NSArray * subStr = [MAC componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@":-"]];
    NSMutableArray * subStr_M = [[NSMutableArray alloc] initWithCapacity:0];
    for (NSString * str in subStr) {
        if (1 == str.length) {
            NSString * tmpStr = [NSString stringWithFormat:@"0%@", str];
            [subStr_M addObject:tmpStr];
        } else {
            [subStr_M addObject:str];
        }
    }
    
    NSString * formateMAC = [subStr_M componentsJoinedByString:@":"];
    [subStr_M release];
    return [formateMAC uppercaseString];
}