如何在 iOS 13 设备上获取Wi-Fi名称(SSID)

3

我有一个 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, 先感谢您的帮助!

1个回答

5

在iOS 14上使用提供的代码时,我得到了以下错误:

nehelper发送了无效的结果代码[1]以获取Wi-Fi信息请求

查找该错误会引导我到这个问题

解决方案

请求应用必须符合以下要求之一:

该应用使用核心位置,并具有使用位置信息的用户授权。

该应用程序使用NEHotspotConfiguration API配置当前Wi-Fi网络。

该应用程序已安装活动VPN配置。

未满足上述任何要求的应用程序将接收到以下返回值:

针对iOS 12或更早版本链接的应用程序将收到带有伪值的字典。在这种情况下,SSID为Wi-Fi(或中国区域中的WLAN),BSSID为00:00:00:00:00:00。

针对iOS 13或更高版本链接的应用程序将收到NULL。

重要提示:

要使用此功能,必须在Xcode中启用访问WiFi信息功能的iOS 12或更高版本应用程序。

我还确认了这实际上在请求位置权限后,在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))")
    }
  }
}

输出结果:SSID:YaMomsWiFi

别忘了在你的plist文件中包含wifi权限和所需的位置权限密钥。


从iOS 14开始,CNCopyCurrentNetworkInfo已被弃用,不再建议使用。请参考:https://developer.apple.com/documentation/systemconfiguration/1614126-cncopycurrentnetworkinfo - shaqir saiyed
你确定吗?因为官方的苹果开发者文档中说在iOS14中已经被弃用了。 - shaqir saiyed
在iOS 14上,您应该使用以下内容:https://developer.apple.com/documentation/networkextension/nehotspotnetwork/3666511-fetchcurrentwithcompletionhandle - srgtuszy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接