import Foundation
import SystemConfiguration.CaptiveNetwork
public class SSID {
class func fetchSSIDInfo() -> String {
var currentSSID = ""
if let interfaces = 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
}
}
如果您运行的是iOS 12,则需要执行额外的步骤 . 我've been struggling to make this code work and finally found this on Apple'的网站:"Important To use this function in iOS 12 and later, enable the Access WiFi Information capability for your app in Xcode. When you enable this capability, Xcode automatically adds the Access WiFi Information entitlement to your entitlements file and App ID." https://developer.apple.com/documentation/systemconfiguration/1614126-cncopycurrentnetworkinfo
8 回答
从iOS 7或8开始,您可以执行此操作,它利用ARC和模块,它们将自动链接到所需的框架中:
(这是为iOS 4.1编写的代码示例的现代化 . 唯一的变化是引入更清晰的变量名称并采用ARC和模块 . )
示例输出:
请注意,模拟器上不支持ifs . 在您的设备上测试 .
在4.1之前,您可能会通过系统配置字典获得一些运气 . 例如,在我的Mac上使用
scutil
:iOS 12
您必须从功能启用访问wifi信息 .
这是清理过的ARC版本,基于@ elsurudo的代码:
更新iOS 10及更高版本
iOS 10中不再弃用CNCopySupportedInterfaces . (API Reference)
您需要导入 SystemConfiguration/CaptiveNetwork.h 并将 SystemConfiguration.framework 添加到目标的链接库(在构建阶段) .
这是swift _2784385中的代码片段:
( Important: CNCopySupportedInterfaces在模拟器上返回nil . )
对于Objective-c,请参阅Esad's answer here and below
更新iOS 9
截至iOS 9,Captive Network已被弃用* . (source)
*不再在iOS 10中弃用,请参见上文 .
建议你使用NEHotspotHelper(source)
您需要通过networkextension@apple.com向Apple发送电子邮件并申请权利 . (source)
示例代码(Not my code. See Pablo A's answer):
旁注:是的,他们弃用了iOS 9中的CNCopySupportedInterfaces,并改变了他们在iOS 10中的地位 . 我与一位Apple网络工程师进行了交谈,之后很多人提交了Radars并在Apple Developer论坛上发表了这个问题 .
这适用于我的设备(不是模拟器) . 确保添加系统配置框架 .
此代码可以很好地获取SSID .
这是结果:
}
如果您运行的是iOS 12,则需要执行额外的步骤 . 我've been struggling to make this code work and finally found this on Apple'的网站:"Important To use this function in iOS 12 and later, enable the Access WiFi Information capability for your app in Xcode. When you enable this capability, Xcode automatically adds the Access WiFi Information entitlement to your entitlements file and App ID." https://developer.apple.com/documentation/systemconfiguration/1614126-cncopycurrentnetworkinfo
请参阅CaptiveNetwork中的CNCopyCurrentNetworkInfo:http://developer.apple.com/library/ios/#documentation/SystemConfiguration/Reference/CaptiveNetworkRef/Reference/reference.html .
这是简短而甜蜜的Swift版本 .
请记住链接和导入框架:
定义方法:
在需要时调用方法:
如其他地方所述,这仅适用于您的iDevice . 当不在WiFi上时,该方法将返回nil - 因此是可选的 .