Hey,
I want to connect to an Wifi network setup by my IoT device.
I am using the following code to do so:
public class WifiUtil: NSObject{
private func connect(...) {
if #available(iOS 11.0, *) {
let configuration = initHotspotConfiguration(ssid: sSSID, passphrase: sPassword, security: sSecurity)
configuration.joinOnce = bJoinOnce ?? false
NEHotspotConfigurationManager.shared.apply(configuration) { [weak self] (error) in
guard let this = self else {
print("WiFi network not found")
result(false)
return
}
this.getSSID { (sSSID) -> () in
if (error != nil) {
if (error?.localizedDescription == "already associated.") {
print("Connected to '\(sSSID ?? "<Unknown Network>")'")
result(true)
} else {
print("Not Connected")
result(false)
}
} else if let ssid = sSSID {
print("Connected to " + ssid)
// ssid check is required because if wifi not found (could not connect) there seems to be no error given
result(ssid == sSSID)
} else {
print("WiFi network not found")
result(false)
}
}
}
} else {
print("Not Connected")
result(nil)
return
}
}
private func getSSID(result: @escaping (String?) -> ()) {
if #available(iOS 14.0, *) {
NEHotspotNetwork.fetchCurrent(completionHandler: { currentNetwork in
result(currentNetwork?.ssid);
})
} else {
if let interfaces = CNCopySupportedInterfaces() as NSArray? {
for interface in interfaces {
if let interfaceInfo = CNCopyCurrentNetworkInfo(interface as! CFString) as NSDictionary? {
result(interfaceInfo[kCNNetworkInfoKeySSID as String] as? String)
return
}
}
}
result(nil)
}
}
}
The code basically calls NEHotspotConfigurationManager.shared.apply
and the checks if WiFi network is same as requested with NEHotspotNetwork.fetchCurrent
. This is as per the docs:
- Apple Docs for
apply(_:completionHandler:)
The system calls your completion handler when it has applied the Wi-Fi level configuration. A successful configuration doesnʼt mean the device has joined that Wi-Fi network. To get the current Wi-Fi state, call fetchCurrent(completionHandler:).
I am getting the following error while fetching the SSID of current network: [] NEHotspotNetwork nehelper sent invalid result code [1] for Wi-Fi information request
. But the phone connects to the network successfully.
I added some delay (incremental 1s upto 15s) before checking - it works sometimes but not always.
Strangely, when I make the connect
request twice - it always works the second time.
Any help to fix this will be appreciated. Thanks in advance.