Im trying to use this code to get SSID
import Foundation
import SystemConfiguration.CaptiveNetwork
public class SSID {
class func getSSID() -> String
In Swift 3 (works in real device and simulator):
import SystemConfiguration.CaptiveNetwork
internal class SSID {
class func fetchSSIDInfo() -> String {
var currentSSID = ""
if let interfaces:CFArray = CNCopySupportedInterfaces() {
for i in 0..<CFArrayGetCount(interfaces){
let interfaceName: UnsafeRawPointer = CFArrayGetValueAtIndex(interfaces, i)
let rec = unsafeBitCast(interfaceName, to: AnyObject.self)
let unsafeInterfaceData = CNCopyCurrentNetworkInfo("\(rec)" as CFString)
if unsafeInterfaceData != nil {
let interfaceData = unsafeInterfaceData! as Dictionary!
currentSSID = ((interfaceData as? [String : AnyObject])?["SSID"])! as! String
}
}
}
return currentSSID
}
}
Usage:
SSID.fetchSSIDInfo()
//will return "" if no connected wifi or running in simulator
The following function return the wifi name and the Mac address
func getNetworkInfo()->(success:Bool,ssid:String,mac:String){
var currentSSID:String = ""
var macAdrees:String = ""
var succes:Bool = false
let interfaces:CFArray! = CNCopySupportedInterfaces()
for i in 0..<CFArrayGetCount(interfaces){
let interfaceName: UnsafePointer<Void>
= CFArrayGetValueAtIndex(interfaces, i)
let rec = unsafeBitCast(interfaceName, AnyObject.self)
let unsafeInterfaceData = CNCopyCurrentNetworkInfo("\(rec)")
if unsafeInterfaceData != nil {
let interfaceData = unsafeInterfaceData! as Dictionary!
currentSSID = interfaceData["SSID"] as! String
macAdrees = interfaceData["BSSID"] as! String
succes = true
} else {
currentSSID = ""
}
}
return (succes, currentSSID, macAdrees)
}
This code works fine. You will note some warning in your development target >= iOS9
All the presented at the moment solutions seems rather complex, with ugly unsafe casts.
I was able to craft such a concise solution (with no black magic at all):
import Foundation
import SystemConfiguration.CaptiveNetwork
func getSSID() -> String? {
var ssid: String?
if let interfaces = CNCopySupportedInterfaces() as NSArray? {
for interface in interfaces {
if let interfaceInfo = CNCopyCurrentNetworkInfo(interface as! CFString) as NSDictionary? {
ssid = interfaceInfo[kCNNetworkInfoKeySSID as String] as? String
break
}
}
}
return ssid
}
Swift 4 version
import SystemConfiguration.CaptiveNetwork
func getSSID() -> String? {
guard let interface = (CNCopySupportedInterfaces() as? [String])?.first,
let unsafeInterfaceData = CNCopyCurrentNetworkInfo(interface as CFString) as? [String: Any],
let ssid = unsafeInterfaceData["SSID"] as? String else{
return nil
}
return ssid
}