swiftuilocationwifissid

How to get SSID WiFi information?


I remember using this code on Xcode 14 (to print the SSID of the WIFI where the device is connected) without problem:

import Foundation
import SystemConfiguration.CaptiveNetwork
import NetworkExtension

struct MainView: View {
       
    @State var newlocationManager = NewLocationManager()

    var body: some View {
        VStack {
            
            Button() {
                getWIFISSID()
            }label: {
                Text("get SSID")
            }
        }.task {
            
            try? await newlocationManager.requestUserAuthorization()
            try? await newlocationManager.startCurrentLocationUpdates()
            // remember that nothing will run here until the for try await loop finishes
            
        }
    }
       
    func getWIFISSID()  {
        NEHotspotNetwork.fetchCurrent(completionHandler: { (network) in
            if let unwrappedNetwork = network {
                let networkSSID = unwrappedNetwork.ssid
                 print("Network: \(networkSSID) and signal strength %d",  unwrappedNetwork.signalStrength)
            } else {
                print("No available network")
            }
        })
    }
}

#Preview {
    MainView()

The code for the NewLocationManager is:

@Observable
class NewLocationManager {
    var location: CLLocation? = nil
    
    private let locationManager = CLLocationManager()
    
    func requestUserAuthorization() async throws {
        locationManager.requestWhenInUseAuthorization()
    }
    
    func startCurrentLocationUpdates() async throws {
        for try await locationUpdate in CLLocationUpdate.liveUpdates() {
            guard let location = locationUpdate.location else { return }

            self.location = location
        }
    }
}

As needed I have the correct location permission and the "Access WIFI Information" capability. But I got:

NEHotspotNetwork failed to communicate to helper server for Wi-Fi information request
NEHotspotNetwork nehelper sent invalid result code [5] for Wi-Fi information request
No available network

Somebody has got the SSID wifi information of an iOS device successfully on Xcode 15?


Solution

  • Got working now.

    I just forgot to add the import CoreLocation library on the MainView.

    Just adding this line it works ok and the program prints:

    Network: VM7687400 and signal strength %d 0.0 as expected.