-1

I need to get ssid of currently connected network. The reason I need this is to enable my app to perform certain functions when connected to a specific network.

    func getInterfaces() -> Bool {
        
        guard let unwrappedCFArrayInterfaces = CNCopySupportedInterfaces() else {
            
            print("this must be a simulator, no interfaces found")
            
            return false
            
        }
        
        guard let swiftInterfaces = (unwrappedCFArrayInterfaces as NSArray) as? [String] else {
            
            print("System error: did not come back as array of Strings")
            
            return false
            
        }
        
        for interface in swiftInterfaces {
            
            print("Looking up SSID info for \(interface)") // en0
            
            guard let unwrappedCFDictionaryForInterface = CNCopyCurrentNetworkInfo(interface as CFString) else {
                
                print("System error: \(interface) has no information")
                
                return false
                
            }
            
            guard let SSIDDict = (unwrappedCFDictionaryForInterface as NSDictionary) as? [String: AnyObject] else {
                
                print("System error: interface information is not a string-keyed dictionary")
                
                return false
                
            }
            
            for d in SSIDDict.keys {
                
                print("\(d): >>>>>> \(SSIDDict[d]!)")
                
            }
            
        }
        
        return true
        
    }

I have tried this code but it is returning nil

HangarRash
  • 7,314
  • 5
  • 5
  • 32
Renuka
  • 3
  • 2
  • 1
    Is this for iOS? macOS? Linux? What's returning `nil`? Your code returns either `true` or `false`, not `nil`? Please update your question with a lot more details about what your code actually does at runtime. Show the output of your `print` statements. – HangarRash Dec 23 '22 at 15:14
  • Possible duplicate: https://stackoverflow.com/questions/64676100/how-to-get-ssid-of-currently-connected-wifi-network-in-swift-ios-14 – MannyCalavera27 Dec 23 '22 at 16:29

1 Answers1

0

For iOS try:

import SystemConfiguration.CaptiveNetwork

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
            }
            print(ssid)
            return ssid
        }
    }

But, You need add entitlement Access WiFi Information Boolean YES

Codl
  • 52
  • 5