You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

iOS 16+下获取SSID返回空值/nil的适配问题求助

iOS 16+下获取SSID返回空值/nil的适配问题求助

各位大佬好,我最近碰到了一个iOS版本适配的棘手问题:在iOS 16之前,用旧代码获取当前WiFi的SSID一直很正常,但升级到iOS 16及更高版本后,拿到的SSID总是空值或者nil,试了好几种方法都没解决,想请教下大家有没有类似的踩坑经历或者解决思路?

旧代码(iOS 16以下稳定可用)

这段代码在iOS 16及以下系统能正常获取到SSID:

func fetchSSIDInfo() -> String {
    var currentSSID = ""
    if let interfaces = 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 let interfaceData = unsafeInterfaceData as? [String: AnyObject] {
                currentSSID = interfaceData["SSID"] as? String ?? ""
                debugPrint("fetchSSIDInfo 4", BUtility().currentDateInMillisec())
                debugPrint("ssid=\(currentSSID)")
            }
        }
    }
    return currentSSID
}

我尝试的新代码(iOS 16+仍返回空值)

查资料后知道iOS 14+推荐用NEHotspotNetwork.fetchCurrent API,于是写了带异步等待的新代码,同时保留了旧API的降级逻辑,但不管走新API还是降级到旧逻辑,返回的SSID都是空的:

func fetchSSIDInfo(_ timeout: TimeInterval = 1.0) -> String {
    // iOS 14+ path (NEHotspotNetwork.fetchCurrent is async callback)
    if #available(iOS 14.0, *) {
        let sem = DispatchSemaphore(value: 0)
        var ssidResult: String?
        
        NEHotspotNetwork.fetchCurrent { network in
            if let s = network?.ssid, !s.isEmpty {
                ssidResult = s
            }
            sem.signal()
        }
        
        // Wait for the callback (bounded by timeout)
        _ = sem.wait(timeout: .now() + timeout)
        
        if let s = ssidResult, !s.isEmpty {
            return s
        }
        // If NEHotspotNetwork didn't return an SSID (or timed out), fall through to CaptiveNetwork fallback.
    }
    
    // Fallback for older iOS or if NEHotspotNetwork didn't provide SSID
    if let interfaces = CNCopySupportedInterfaces() as? [String] {
        for interface in interfaces {
            if let info = CNCopyCurrentNetworkInfo(interface as CFString) as? [String: Any],
               let ssid = info["SSID"] as? String, !ssid.isEmpty {
                return ssid
            }
        }
    }
    return ""
}

已做的权限检查

我已经在Info.plist中添加了com.apple.developer.networking.wifi-info权限,也在开发者后台开启了对应的WiFi访问能力,但问题依然存在。

有没有大佬能帮我排查下问题出在哪?或者有没有其他可靠的方式在iOS 16+上获取SSID?麻烦大家了!

火山引擎 最新活动