From fcc1b93bb2ee478491c1bcf3dc7b2280286d1b48 Mon Sep 17 00:00:00 2001 From: fuyoufang Date: Mon, 2 Aug 2021 11:43:02 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=20wifi=20=E5=90=8D=E7=A7=B0?= =?UTF-8?q?=E8=8E=B7=E5=8F=96=E9=94=99=E8=AF=AF=E7=9A=84bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- WiFiPassword/ContentView.swift | 4 ++-- WiFiPassword/Tools/QRCode.swift | 2 +- WiFiPassword/Tools/WiFiHelper.swift | 35 +++++++++++++++++++++++++++-- 3 files changed, 36 insertions(+), 5 deletions(-) diff --git a/WiFiPassword/ContentView.swift b/WiFiPassword/ContentView.swift index 8106fba..1d3aa4a 100644 --- a/WiFiPassword/ContentView.swift +++ b/WiFiPassword/ContentView.swift @@ -67,12 +67,12 @@ struct ContentView: View { do { ssid = try WiFiHelper.getSsid() } catch { - self.errorMsg = "未获取到 WiFi" + self.errorMsg = "未获取到 WiFi 信息,请确保当前 Mac 正在链接 WiFI 网络。" return nil } guard let password = WiFiHelper.getPassword(ssid: ssid) else { - self.errorMsg = "未获取到 Password" + self.errorMsg = "未获取到 Password,请输入正确的管理员账号、密码。" return nil } debugPrint("wifi: \(ssid), password:\(password)") diff --git a/WiFiPassword/Tools/QRCode.swift b/WiFiPassword/Tools/QRCode.swift index fa1e4d6..002274a 100644 --- a/WiFiPassword/Tools/QRCode.swift +++ b/WiFiPassword/Tools/QRCode.swift @@ -8,8 +8,8 @@ /* 下面代码来自 https://github.com/aschuch/QRCode + 其他资料 https://stackoverflow.com/questions/61589783/resize-ciimage-to-an-exact-size - https://nshipster.com/image-resizing/ */ diff --git a/WiFiPassword/Tools/WiFiHelper.swift b/WiFiPassword/Tools/WiFiHelper.swift index 2f22a55..b999eec 100644 --- a/WiFiPassword/Tools/WiFiHelper.swift +++ b/WiFiPassword/Tools/WiFiHelper.swift @@ -17,12 +17,43 @@ struct WiFiHelper { debugPrint("no WiFi") throw AppError.noWiFiInformation } + + /* + + let command = "\(path) -I | awk '/ SSID/ {{print substr($0, index($0, $2))}}'" + + awk '/ SSID/ {{print substr($0, index($0, $2))}}' + 解释: + 1. / SSID/: 为模式,标识包含 " SSID" 的行 + 2. substr($0, index($0, $2)):为截取 $0 从 index($0, $2) 开始到最后的字符串, + 举例来说,加入字符串为:" SSID: 10-floor-5G", + 则 $0 为 " SSID: 10-floor-5G",$1 为 "SSID:", $2 为 "10-floor-5G", + 参考资料 + https://www.cnblogs.com/Berryxiong/p/4807640.html + */ + // + let command = "\(path) -I" + + guard let result = shell(command) else { + throw AppError.noWiFiInformation + } + + let ssidLine: String? = result.components(separatedBy: "\n") + .first { (line: String) -> Bool in + return line.contains(" SSID:") + } - let command = "\(path) -I | awk '/ SSID/ {{print substr($0, index($0, $2))}}'" - guard let ssid = shell(command) else { + guard let line = ssidLine, let range = line.range(of: "SSID:") else { + throw AppError.noWiFiInformation + } + + let ssid = line[range.upperBound...].trimmingCharacters(in: .whitespacesAndNewlines) + + guard ssid.count > 0 else { throw AppError.noWiFiInformation } return ssid + } static func getPassword(ssid: String) -> String? {