正在尝试获取当前设备的 SSID。我已经找到了很多关于如何做到这一点的例子,但是我正在努力让 CNCopySupportedInterfaces 自动完成。我的 swift 文件顶部有“import SystemConfiguration”但没有成功。似乎无法弄清楚我做错了什么。
最佳答案
iOS 12
您必须启用从功能中访问 WiFi 信息。
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. Documentation link
您需要:import SystemConfiguration.CaptiveNetwork
在幕后,CaptiveNetwork 是一个位于 SystemConfiguration 框架内的 C 头文件 (.h):
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/System/Library/Frameworks/SystemConfiguration.framework/Headers/CaptiveNetwork.h
如果你了解 Objective-C,这会更深入:
iPhone get SSID without private library
您必须使用笨拙的语法从任何纯 C API 桥接,因此需要以下内容:
for interface in CNCopySupportedInterfaces().takeRetainedValue() as! [String] {
println("Looking up SSID info for \(interface)") // en0
let SSIDDict = CNCopyCurrentNetworkInfo(interface).takeRetainedValue() as! [String : AnyObject]
for d in SSIDDict.keys {
println("\(d): \(SSIDDict[d]!)")
}
}
SWIFT 2.2 和 3.0 附录
CFxxx
数据类型现在桥接到 native Objective-C 运行时,消除了令人头疼的 retain
调用。然而,可为空的指针会产生 Optionals,因此事情不会变得更短。至少,很清楚发生了什么,加上 nil
帮助我们识别模拟器。另一个答案使用了大量的位转换和不安全的操作,这似乎是非 Swiftian 的,所以我提供这个。
func getInterfaces() -> Bool {
guard let unwrappedCFArrayInterfaces = CNCopySupportedInterfaces() else {
print("this must be a simulator, no interfaces found")
return false
}
guard let swiftInterfaces = (unwrappedCFArrayInterfaces as NSArray) as? [String] else {
print("System error: did not come back as array of Strings")
return false
}
for interface in swiftInterfaces {
print("Looking up SSID info for \(interface)") // en0
guard let unwrappedCFDictionaryForInterface = CNCopyCurrentNetworkInfo(interface) else {
print("System error: \(interface) has no information")
return false
}
guard let SSIDDict = (unwrappedCFDictionaryForInterface as NSDictionary) as? [String: AnyObject] else {
print("System error: interface information is not a string-keyed dictionary")
return false
}
for d in SSIDDict.keys {
print("\(d): \(SSIDDict[d]!)")
}
}
return true
}
成功输出:
SSID 数据:<57696c6d 79>
BSSID:12:34:56:78:9a:bc
SSID:你的SSID在这里
关于ios - Swift CNCopySupportedInterfaces 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31755692/