본문 바로가기
프로그래밍/iOS-Swift

[SWIFT] WIFI Info

by 채연2 2021. 4. 7.

1. Info.plist 작성 (위치 접근 권한)

 

 

 

2. SSID class

public class SSID {
    class func fetchNetworkInfo() -> [NetworkInfo]? {
        if let interfaces: NSArray = CNCopySupportedInterfaces() {
            var networkInfos = [NetworkInfo]()
            for interface in interfaces {
                let interfaceName = interface as! String
                var networkInfo = NetworkInfo(interface: interfaceName,
                                              success: false,
                                              ssid: nil,
                                              bssid: nil)
                if let dict = CNCopyCurrentNetworkInfo(interfaceName as CFString) as NSDictionary? {
                    networkInfo.success = true
                    networkInfo.ssid = dict[kCNNetworkInfoKeySSID as String] as? String
                    networkInfo.bssid = dict[kCNNetworkInfoKeyBSSID as String] as? String
                }
                networkInfos.append(networkInfo)
            }
            return networkInfos
        }
        return nil
    }
}

 

 

 

3. NetworkInfo struct

struct NetworkInfo {
    var interface: String
    var success: Bool = false
    var ssid: String?
    var bssid: String?
}

 

 

 

4. viewDidLoad()

import UIKit
import CoreLocation
import SystemConfiguration.CaptiveNetwork

class ViewController: UIViewController, CLLocationManagerDelegate {
    ...
    var locationManager = CLLocationManager()
    var currentNetworkInfos: Array<NetworkInfo>? {
        get {
            return SSID.fetchNetworkInfo()
        }
    }
    ...

    override func viewDidLoad() {
        super.viewDidLoad()
        
        if #available(iOS 13.0, *) {
            let status = CLLocationManager.authorizationStatus()
            if status == .authorizedWhenInUse {
                print("status == .authorizedWhenInUse")
                updateWiFi()
            } else {
                print("status != .authorizedWhenInUse")
                locationManager.delegate = self
                locationManager.requestWhenInUseAuthorization()
            }
        } else {
            print("else")
            updateWiFi()
        }
    }
    ...
}

 

 

 

5. updateWiFi()

func updateWiFi() {
    print("updateWiFi()")
    print("SSID: \(currentNetworkInfos?.first?.ssid ?? "")")
    wifiLabel.text = currentNetworkInfos?.first?.ssid
    wifiLabel2.text = currentNetworkInfos?.first?.bssid
}

 

 

 

6. locationManager()

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    print("locationManager()")
    if status == .authorizedWhenInUse {
        updateWiFi()
    }
}

 

 

 

 

참고 : github.com/HackingGate/iOS13-WiFi-Info/blob/master/Check-WiFI/ViewController.swift

 

320x100

댓글