ios在模拟器和设备中检测连接的网络名称

时间:2014-08-04 06:43:58

标签: ios

我试图使用此代码获取iOS模拟器所连接的网络名称

-(void)getNetworkName
{
 CFArrayRef myArray = CNCopySupportedInterfaces();
    CFDictionaryRef myDict = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));
    NSDictionary *dict = ( NSDictionary*) myDict;
    NSString* ssid = [dict objectForKey:@"SSID"];

    NSString * netWorkName = [NSString stringWithFormat:@"%@",ssid];

    NSLog(@"%@",netWorkName);

}

它适用于设备,但在iOS模拟器上运行时

 CFArrayRef myArray = CNCopySupportedInterfaces();

抛出exc_bad_acess请帮我在模拟器中获取网络名称。

1 个答案:

答案 0 :(得分:1)

CNCopySupportedInterfaces()在模拟器中返回nil。您正试图访问CFArrayGetValueAtIndex(myArray, 0)中数组的第一个元素,这会导致应用崩溃。

尝试以下代码。它仅在具有某个元素的情况下访问该数组。

- (NSString *)getNetworkName {
    // Does not work on the simulator.
    NSString *ssid = nil;
    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
    for (NSString *ifnam in ifs) {
        NSDictionary *info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        if (info[@"SSID"]) {
            ssid = info[@"SSID"];
        }
    }
    return ssid;
}