经过这个stackoverflow问答的解释,在Sequoia
(15)版本中,获取SSID的方式发生了变化,无论是否给予权限,原本的基于CWWiFiClient
API的方法似乎都只会直接返回空值。目前可能唯一能用的方式是使用命令获取。
1
| system_profiler SPAirPortDataType | awk '/Current Network/ {getline;$1=$1;print $0 | "tr -d ':'";exit}'
|
来源:https://stackoverflow.com/questions/78994709/how-to-get-the-current-wi-fi-ssid-in-swift-on-macos
但是这个获取SSID的方式实在太慢了,因此@David P.提出了一个更快的方式
1
| ipconfig getsummary "$(networksetup -listallhardwareports | awk '/Wi-Fi|AirPort/{getline; print $NF}')" | grep ' SSID : ' | awk -F ': ' '{print $2}'
|
来源:https://stackoverflow.com/a/79172061/16759589
将其铺平后为
1
| networksetup -listallhardwareports | awk '/Wi-Fi|AirPort/{getline; print $NF}'|xargs ipconfig getsummary|grep ' SSID : ' | awk -F ': ' '{print $2}'
|
在查阅其他开源项目的实现时发现存在项目直接假设en0
作为Wi-Fi适配器设备的情况,但是这位用户仍然进行了查找Wi-Fi或者AirPort适配器设备的过程。由于我对macOS平台不熟悉,所以我并不能确定这是否是一个当前情况下较好的解决方案。以下是一个其他来源的,假设en0
永远存在且为Wi-Fi适配器设备的情况的命令。
1
| ipconfig getsummary en0 | awk -F ' SSID : ' '/ SSID : / {print $2}'
|
来源:https://apple.stackexchange.com/a/475678
如果假设en0,同时直接使用awk得到结果的话,经过我的测试,时间开销大约为前文列出的查找Wi-Fi适配器设备的方式的1/3。
为了便于在swift中使用,将其封装为一个函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| func getCurrentWiFiSSID(interfaceName:String? = "en0") -> String? { var command = ""; if(interfaceName == nil){ command = #"networksetup -listallhardwareports | awk '/Wi-Fi|AirPort/{getline; print $NF}' | xargs ipconfig getsummary"# } else{ command = "ipconfig getsummary \(interfaceName ?? "en0")" } command += #" | awk -F ' SSID : ' '/ SSID : / {print $2}'"# let process = Process() let pipe = Pipe() process.standardOutput = pipe process.standardError = pipe process.arguments = ["-c", command] process.launchPath = "/bin/bash" process.launch() process.waitUntilExit() let data = pipe.fileHandleForReading.readDataToEndOfFile() guard let output = String(data: data, encoding: .utf8)? .trimmingCharacters(in: .whitespacesAndNewlines), !output.isEmpty else { return nil } return output }
|
使用案例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import Foundation import Network
let monitor = NWPathMonitor() let queue = DispatchQueue(label: "NetworkMonitorQueue")
var lastStatus: NWPath.Status = .unsatisfied
monitor.pathUpdateHandler = { path in if path.status != lastStatus { lastStatus = path.status print("Network changed!") if let ssid = getCurrentWiFiSSID(interfaceName: nil) { print("Current Wi-Fi SSID: \(ssid)") } else { print("Not connected to Wi-Fi") } } }
monitor.start(queue: queue) RunLoop.main.run()
|