Get the currently connected WiFi informations in Swift 4.x

i0S Swift Issue

While developing applications many times you need to get the connection information of Wifi or Access Point to serve many different purposes. The following guide will help you get the SSID, BSSID (MAC Address) and Interface Name information of Wifi or Access Point that your iOS device is connected to them.

First, You must turn on “Access WiFi Information” from Xcode’s “Capabilities

Turn On "Access WiFi Information" from Xcode's "Capabilities"
Turn On “Access WiFi Information” from Xcode’s “Capabilities”

The following code will return an array containing Wifi information including SSID, BSSID (MAC) and Interface Name:

struct WifiInfo {
        public let interface:String
        public let ssid:String
        public let bssid:String
        init(_ interface:String, _ ssid:String,_ bssid:String) {
            self.interface = interface
            self.ssid = ssid
            self.bssid = bssid
        }
    }
    
    func getWifiInfo() -> Array<WifiInfo> {
        guard let interfaceNames = CNCopySupportedInterfaces() as? [String] else {
            return []
        }
        let wifiInfo:[WifiInfo] = interfaceNames.compactMap{ name in
            guard let info = CNCopyCurrentNetworkInfo(name as CFString) as? [String:AnyObject] else {
                return nil
            }
            guard let ssid = info[kCNNetworkInfoKeySSID as String] as? String else {
                return nil
            }
            guard let bssid = info[kCNNetworkInfoKeyBSSID as String] as? String else {
                return nil
            }
            return WifiInfo(name, ssid,bssid)
        }
        return wifiInfo
    }

Use print(getWifiInfo()) to view logs, like this:

(TODO)

Or when you just want to get the SSID of Wifi or Access Point, you can use the following short code:

func currentSSIDs() -> [String] {
        guard let interfaceNames = CNCopySupportedInterfaces() as? [String] else {
            return []
        }
        return interfaceNames.compactMap { name in
            guard let info = CNCopyCurrentNetworkInfo(name as CFString) as? [String:AnyObject] else {
                return nil
            }
            guard let ssid = info[kCNNetworkInfoKeySSID as String] as? String else {
                return nil
            }
            return ssid
        }
    }