Im trying to use this code to get SSID
import Foundation
import SystemConfiguration.CaptiveNetwork
public class SSID {
class func getSSID() -> String
I have seen a lot of versions of this very popular question using the SystemConfiguration
framework. Reading through this list of answers I've found that they're all over the place. Unsafe-bit casting, magic strings, weird coercion. Any time an API returns CFArray
or CFDictionary
use toll-free bridging to get an NS{Array,Dictionary}
. It allows you to avoid some of the uglier aspects (in the context of Swift) of CoreFoundation
. Also you should use the constants defined in the header for the SSID and BSSID dictionary values. Absolutely no need for the Unsafe types here, all of the data types are well-defined. That said, the CaptiveNetwork version of this code is deprecated in iOS 14 and it is recommended you use the NetworkExtension
framework instead.
import NetworkExtension
NEHotspotNetwork.fetchCurrent { hotspotNetwork in
if let ssid = hotspotNetwork?.ssid {
print(ssid)
}
}
import SystemConfiguration.CaptiveNetwork
func getWiFiNetwork() -> (ssid: String, bssid: String)?
{
var wifiNetwork: (ssid: String, bssid: String)?
if let interfaces = CNCopySupportedInterfaces() as NSArray? {
for interface in interfaces {
let name = interface as! CFString
if let interfaceData = CNCopyCurrentNetworkInfo(name) as NSDictionary? {
if let ssid = interfaceData[kCNNetworkInfoKeySSID] as? String,
let bssid = interfaceData[kCNNetworkInfoKeyBSSID] as? String {
wifiNetwork = (ssid: ssid, bssid: bssid)
}
}
}
}
return wifiNetwork
}
In terms of user permissions you have possibilities, but you need one of four defined in the documentation for CNCopyCurrentNetworkInfo or fetchCurrent - for most cases I assume you will need to add CoreLocation and ask for permission to use the user's location. For example, Privacy - Location When In Use Usage Description
in the Info.plist needs a reason for why you require the user's location and then you must make the call to request the user authorization dialog.
import CoreLocation
CLLocationManager().requestWhenInUseAuthorization()
Your app also need the entitlement - com.apple.developer.networking.wifi-info
which is added in Signing and Capabilities section of the project and is called Access WiFi Information. When using NEHotspotNetwork
method there is an additional Network Extensions entitlement required.