我正在尝试显示所有可用的WIFI连接.它不起作用.这是我的代码:
import Foundation import CoreWLAN var cwInterface = CWInterface() do { let routers = try cwInterface.scanForNetworksWithSSID(nil) print(routers) } catch let error as NSError { print("Error: \(error.localizedDescription)") }
我没有得到任何结果.我做错了什么?
如果使用接口名称初始化CWInterface,它将起作用,例如“en1”.
但最好不使用带编码的名称,因此我们还将使用CWWiFiClient.sharedWiFiClient().interface()返回默认的WIFI接口.
管理所有这些的类的示例:
class Discovery { var currentInterface: CWInterface var interfacesNames: [String] = [] var networks: Set<CWNetwork> = [] // Failable init using default interface init?() { if let defaultInterface = CWWiFiClient.sharedWiFiClient().interface(),name = defaultInterface.interfaceName { self.currentInterface = defaultInterface self.interfacesNames.append(name) self.findNetworks() } else { return nil } } // Init with the literal interface name,like "en1" init(interfaceWithName name: String) { self.currentInterface = CWInterface(interfaceName: name) self.interfacesNames.append(name) self.findNetworks() } // Fetch detectable WIFI networks func findNetworks() { do { self.networks = try currentInterface.scanForNetworksWithSSID(nil) } catch let error as NSError { print("Error: \(error.localizedDescription)") } } }
使用默认界面调用它:
if let discovery = Discovery() { print(discovery.networks) for network in discovery.networks { print(network.ssid!) } }
或者使用接口名称:
let discovery = Discovery(interfaceWithName: "en1") let results = discovery.networks
结果包含所有扫描的网络:
[<CWNetwork: 0x608000001bd0> [ssid=SomeNetworkName,bssid=xxxx,security=WPA Enterprise,RSSi=xx,channel=<CWChannel: 0x600000004fb0> [channelNumber=11(2GHz),channelWidth={20MHz}],ibss=0],etc]