快速尝试了一下,它似乎可以完美重现。
进一步的研究表明这是苹果的一个错误。
所以答案是:你没有做错什么,这是一个错误。
原因似乎是:
...您通过完成处理程序看到的错误是与框架本身相关的错误。一旦请求通过网络扩展框架,到达 Wi-Fi 子系统,错误就会显示给用户,而不是传递给完成处理程序。这是否是一个错误还有待争论。
稍后可以读到:
所以我的 2 个关于 NEHotspot 的错误(46628017 和 46579891)被标记为与 42919071 重复
请参阅此处的整个讨论:https://forums.developer.apple.com/thread/96834 https://forums.developer.apple.com/thread/96834
一些实验
有一个很好的答案:https://stackoverflow.com/a/5198968/2331445 https://stackoverflow.com/a/5198968/2331445
它显示了如何访问有关当前连接的 WIFI 的信息。
正如作者所解释的,您需要添加接入WiFi信息能力对于 iOS > 12。使用上述实验答案中的 getConnectedWifiInfo 方法进行的测试可能如下所示:
import UIKit
import NetworkExtension
import SystemConfiguration.CaptiveNetwork
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func onConnect(_ sender: Any) {
let configuration = NEHotspotConfiguration.init(ssid: "somessid", passphrase: "somepassphrase", isWEP: false)
configuration.joinOnce = true
NEHotspotConfigurationManager.shared.apply(configuration) { [weak self] (error) in
print("error is \(String(describing: error))")
if let error = error {
let nsError = error as NSError
if nsError.domain == "NEHotspotConfigurationErrorDomain" {
if let configError = NEHotspotConfigurationError(rawValue: nsError.code) {
switch configError {
case .invalidWPAPassphrase:
print("password error: \(error.localizedDescription)")
case .invalid, .invalidSSID, .invalidWEPPassphrase,
.invalidEAPSettings, .invalidHS20Settings, .invalidHS20DomainName, .userDenied, .pending, .systemConfiguration, .unknown, .joinOnceNotSupported, .alreadyAssociated, .applicationIsNotInForeground, .internal:
print("other error: \(error.localizedDescription)")
@unknown default:
print("later added error: \(error.localizedDescription)")
}
}
} else {
print("some other error: \(error.localizedDescription)")
}
} else {
print("perhaps connected")
self?.printWifiInfo()
}
}
}
@IBAction func onInfo(_ sender: Any) {
self.printWifiInfo()
}
private func printWifiInfo() {
print("printWifiInfo:")
if let wifi = self.getConnectedWifiInfo() {
if let connectedSSID = wifi["SSID"] {
print("we are currently connected with \(connectedSSID)")
}
print("further info:")
for (k, v) in wifi {
print(". \(k) \(v)")
}
}
print()
}
private func getConnectedWifiInfo() -> [AnyHashable: Any]? {
if let ifs = CFBridgingRetain( CNCopySupportedInterfaces()) as? [String],
let ifName = ifs.first as CFString?,
let info = CFBridgingRetain( CNCopyCurrentNetworkInfo((ifName))) as? [AnyHashable: Any] {
return info
}
return nil
}
}
事实上,如果我运行这段代码,我会得到以下结果:
error is nil
perhaps connected
printWifiInfo:
we are currently connected with somessid
further info:
. SSIDDATA <11111111 22222222 333331333 44444444 55>
. BSSID 70:33:ab:cd:ef:22
. SSID somessid
这个 SO 答案的作者还展示了旧版 iOS 版本的方法。