iOS 12,Swift 4.2更新
您必须在功能选项中启用“访问WiFi信息”。
重要提示
要在 iOS 12 及更高版本中使用此功能,请在 Xcode 中为您的应用程序启用“访问WiFi信息”功能。当您启用此功能时,Xcode 会自动向您的权限文件和应用 ID 添加“访问WiFi信息”权限。 文档链接
Swift4.2
public class SSID {
class func fetchSSIDInfo() -> String {
var currentSSID = ""
if let interfaces = 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 let interfaceData = unsafeInterfaceData as? [String: AnyObject] {
currentSSID = interfaceData["SSID"] as! String
let BSSID = interfaceData["BSSID"] as! String
let SSIDDATA = interfaceData["SSIDDATA"]
debugPrint("ssid=\(currentSSID), BSSID=\(BSSID), SSIDDATA=\(SSIDDATA)")
}
}
}
return currentSSID
}
}
iOS 10更新内容
iOS 10中不再弃用CNCopySupportedInterfaces。 (API参考)
你需要导入SystemConfiguration/CaptiveNetwork.h 并将SystemConfiguration.framework添加到您的目标链接库(在构建阶段下)。
以下是Swift代码片段(RikiRiocma的回答):
import Foundation
import SystemConfiguration.CaptiveNetwork
public class SSID {
class func fetchSSIDInfo() -> String {
var currentSSID = ""
if let interfaces:CFArray! = CNCopySupportedInterfaces() {
for i in 0..<CFArrayGetCount(interfaces){
let interfaceName: UnsafePointer<Void> = CFArrayGetValueAtIndex(interfaces, i)
let rec = unsafeBitCast(interfaceName, AnyObject.self)
let unsafeInterfaceData = CNCopyCurrentNetworkInfo("\(rec)")
if unsafeInterfaceData != nil {
let interfaceData = unsafeInterfaceData! as Dictionary!
currentSSID = interfaceData["SSID"] as! String
}
}
}
return currentSSID
}
}
(重要提示: 在模拟器上,CNCopySupportedInterfaces 返回 nil.)
对于 Objective-c,请参见Esad的回答(此处和下面)
+ (NSString *)GetCurrentWifiHotSpotName {
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;
}
iOS 9更新
iOS 9中弃用了Captive Network。(来源)
*iOS 10中不再弃用,请参见上文。
建议使用NEHotspotHelper。(来源)
您需要发送电子邮件至networkextension@apple.com并请求授权。(来源)
示例代码(非本人代码。请参见Pablo A的答案):
for(NEHotspotNetwork *hotspotNetwork in [NEHotspotHelper supportedNetworkInterfaces]) {
NSString *ssid = hotspotNetwork.SSID;
NSString *bssid = hotspotNetwork.BSSID;
BOOL secure = hotspotNetwork.secure;
BOOL autoJoined = hotspotNetwork.autoJoined;
double signalStrength = hotspotNetwork.signalStrength;
}
附注:是的,在iOS 9中,他们废弃了CNCopySupportedInterfaces,并在iOS 10中扭转了立场。我与一位苹果网络工程师交谈过,这种扭转是在很多人在Apple开发者论坛上提交Radars并发表意见后出现的。