[英]How to fetch SSID in iOS device with iOS 13
我有一個 Objective-C iPhone 應用程序,目前我正在使用下面的代碼來獲取連接的 Wifi 名稱。 但它在 iOS 13 中不起作用。如何在 iOS 13 中獲取連接的 Wifi SSID?
目前我在 Swift 中使用以下代碼:
public class SSID {
class func fetch() -> String {
var currentSSID = ""
if let interfaces = CNCopySupportedInterfaces() {
for i in 0..<CFArrayGetCount(interfaces) {
let interfaceName = 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
let BSSID = interfaceData["BSSID"] as! String
let SSIDDATA = interfaceData["SSIDDATA"] as! String
debugPrint("ssid=\(currentSSID), BSSID=\(BSSID), SSIDDATA=\(SSIDDATA)")
}
}
}
return currentSSID
}
}
但是此代碼在 iOS 13 中返回 nil,提前致謝!
使用 iOS 14 上提供的代碼,我收到以下錯誤:
nehelper sent invalid result code [1] for Wi-Fi information request
搜索那個錯誤把我帶到了這個問題
解決方案:
請求應用程序必須滿足以下要求之一:
該應用程序使用核心位置,並具有用戶使用位置信息的授權。
該應用程序使用 NEHotspotConfiguration API 來配置當前的 Wi-Fi 網絡。
該應用程序已安裝有效的 VPN 配置。
未能滿足上述任何要求的應用會收到以下返回值:
與 iOS 12 或更早版本鏈接的應用程序會收到帶有偽值的字典。 在這種情況下,SSID 為 Wi-Fi(或中國地區的 WLAN),BSSID 為 00:00:00:00:00:00。
與 iOS 13 或更高版本鏈接的應用程序會收到 NULL。
重要的
要使用此 function,鏈接到 iOS 12 或更高版本的應用程序必須在 Xcode 中啟用訪問 WiFi 信息功能。
我還確認,一旦您請求位置許可,這實際上適用於 iOS 14。
import CoreLocation
import UIKit
import SystemConfiguration.CaptiveNetwork
final class ViewController: UIViewController {
var locationManager: CLLocationManager?
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager?.delegate = self
locationManager?.requestAlwaysAuthorization()
}
func getWiFiName() -> 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
}
}
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedAlways || status == .authorizedAlways {
let ssid = self.getWiFiName()
print("SSID: \(String(describing: ssid))")
}
}
}
Output: SSID: YaMomsWiFi
不要忘記在您的 plist 中包含 wifi 權利和必要的密鑰以獲得位置許可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.