使用 Swift 在 iOS 应用程序中显示 SSID

Displaying SSID in iOS App using Swift

我目前正在尝试显示用户连接的 WiFi 的 SSID,并将其与特定的 SSID 进行比较,例如,设置的 SSID 是 'WirelessHotspot'。

当用户连接的WiFi为'WirelessHotspot'时,应用程序会显示已连接到正确的WiFi并显示WiFi名称。

目前,我已经尝试过这段代码,引用自Get SSID in Swift 2

import UIKit

import Foundation
import SystemConfiguration.CaptiveNetwork

public class SSID {
    class func fetchSSIDInfo() ->  String {
        var currentSSID = ""
        if let interfaces:CFArray! = CNCopySupportedInterfaces() {
            for i in 0..<CFArrayGetCount(interfaces){
                let interfaceName: UnsafePointer<Void> = CFArrayGetValueAtIndex(interfaces, i)
                let rec = unsafeBitCast(interfaceName, AnyObject.self)
                let unsafeInterfaceData = CNCopyCurrentNetworkInfo("\(rec)")
                if unsafeInterfaceData != nil {
                    let interfaceData = unsafeInterfaceData! as Dictionary!
                    currentSSID = interfaceData["SSID"] as! String

                }
            }
            self.networkname.text = String(currentSSID)
        }
        return currentSSID
    }
}

class AttendanceScreen: UIViewController {

    @IBOutlet weak var networkname: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

但是,这段代码:

self.networkname.text = String(currentSSID)

会return错误:

Type 'SSID' has no member 'networkname'

那么,我如何在 Swift for iOS 9 中实现这个?提前致谢!

我发现创建一个从 Swift 到 Objective-C 的桥梁会容易得多。

导入框架:

#import <SystemConfiguration/CaptiveNetwork.h>

获取用户连接的 WiFi 的 SSID 的代码:

func getMAC()->(success:Bool,ssid:String,mac:String){

    if let cfa: NSArray = CNCopySupportedInterfaces() {
        for x in cfa {
            if let dict = CFBridgingRetain(CNCopyCurrentNetworkInfo(x as! CFString)) {
                let ssid = dict ["SSID"]!
                let mac  = dict["BSSID"]!
                return (true, ssid as! String, mac as! String)
            }
        }
    }
    return (false,"","")
}

需要时打印并显示在标签中:

let x = getMAC()
    if x.success {
        MAClabel = x.mac
        SSIDlabel = x.ssid
        print(x.mac)
        print (x.ssid)
    }

希望对有此疑问的人有所帮助!