我目前正在尝试显示用户连接的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)
将返回错误:
Type 'SSID' has no member 'networkname'
那么,我如何在Swift for iOS 9中实现这一点呢?提前谢谢!
答案 0 :(得分:1)
我发现创建一个从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)
}
我希望那些有这个问题的人会觉得这很有用!