尝试获取当前设备的SSID。我已经找到了很多有关如何执行此操作的示例,但是我正在努力使CNCopySupportedInterfaces自动完成。我的快速文件顶部有“import SystemConfiguration”,但没有成功。似乎无法弄清楚我在做什么错。

最佳答案

iOS 12

您必须从功能启用访问WiFi信息。



您需要: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数据类型被桥接到本机的Objective-C运行时,从而消除了对retain的费解性。但是,可为空的指针会引起Optionals,因此事情不会变得更短。至少,这很清楚发生了什么,加上nil可帮助我们识别模拟器。另一个答案是使用大量位广播和不安全的操作,这些操作似乎是非Swift的,因此我提供了这一点。
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
}

成功输出:

SSIDDATA:

BSSID:12:34:56:78:9a:bc

SSID:YourSSIDHere

08-15 20:37