Skip to content

Commit

Permalink
修改 wifi 名称获取错误的bug
Browse files Browse the repository at this point in the history
  • Loading branch information
fuyoufang committed Aug 2, 2021
1 parent b23abb9 commit fcc1b93
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 5 deletions.
4 changes: 2 additions & 2 deletions WiFiPassword/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)")
Expand Down
2 changes: 1 addition & 1 deletion WiFiPassword/Tools/QRCode.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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/
*/

Expand Down
35 changes: 33 additions & 2 deletions WiFiPassword/Tools/WiFiHelper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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? {
Expand Down

0 comments on commit fcc1b93

Please sign in to comment.