如何获取SSID(服务集标识符),我已经搜索了几个但没什么用处。是否有人可以提供帮助?
但是,我在ios7中试用了这段代码
-(NSString *)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);
return wifiName;
}
但它无法获得SSID。
答案 0 :(得分:3)
(在Xcode 8和Swift 3上测试过) 首先,您需要添加
@import SystemConfiguration.CaptiveNetwork;
#include <SystemConfiguration/SystemConfiguration.h>
然后,Objective-c代码是
- (NSString *) getSSID {
NSString *wifiName = nil;
NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
for (NSString *ifnam in ifs) {
NSDictionary *info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
if (info[@"SSID"]) {
wifiName = info[@"SSID"];
}
}
return wifiName;}
如果你想使用swift,那么你需要将以下代码添加到bridging-header
#include <ifaddrs.h>
swift(swift 3)的代码是
func fetchSSIDInfo() -> String {
var currentSSID = ""
if let interfaces:CFArray = CNCopySupportedInterfaces() {
for i in 0..<CFArrayGetCount(interfaces){
let interfaceName: UnsafeRawPointer = CFArrayGetValueAtIndex(interfaces, i)
let rec = unsafeBitCast(interfaceName, to: AnyObject.self)
let unsafeInterfaceData = CNCopyCurrentNetworkInfo("\(rec)" as CFString)
if unsafeInterfaceData != nil {
let interfaceData = unsafeInterfaceData! as Dictionary!
currentSSID = ((interfaceData as? [String : AnyObject])?["SSID"])! as! String
}
}
}
return currentSSID
}
答案 1 :(得分:1)
试试这个: (的被修改强>)
- (NSString *)wifiName
{
NSString *wifiName = @"Not Found";
CFArrayRef interfaces = CNCopySupportedInterfaces();
if (interfaces)
{
CFDictionaryRef networkDetails = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(interfaces, 0));
if (networkDetails)
{
wifiName = (NSString *)CFDictionaryGetValue(networkDetails, kCNNetworkInfoKeySSID);
CFRelease(networkDetails);
}
}
return wifiName;
}
答案 2 :(得分:0)
+ (NSString*)SSID
{
NSArray* ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
id info = nil;
for (NSString* ifnam in ifs)
{
info = (__bridge id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
if (info && [info count])
break;
}
return info[@"SSID"];
}