我记得在 Xcode 14 上使用此代码(打印设备连接的 WIFI 的 SSID)没有问题:
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()
NewLocationManager 的代码是:
@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
}
}
}
根据需要我拥有正确的位置权限和“访问WIFI信息”能力。 但我得到了:
NEHotspotNetwork 无法与帮助服务器通信以请求 Wi-Fi 信息
NEHotspotNetwork nehelper 发送了无效的 Wi-Fi 信息请求结果代码 [5]
无可用网络
有人在Xcode 15上成功获取iOS设备的SSID wifi信息吗?
现在开始工作了。
我只是忘记在 MainView 上添加
import CoreLocation
库。
只需添加这一行就可以正常工作并且程序会打印:
Network: VM7687400 and signal strength %d 0.0
正如预期的那样。