투케이2K

9. (ios/swift) 현재 연결된 네트워크 상태 체크 실시 - NWPathMonitor 본문

IOS

9. (ios/swift) 현재 연결된 네트워크 상태 체크 실시 - NWPathMonitor

투케이2K 2021. 10. 17. 11:11

[개발 환경 설정]

개발 툴 : XCODE

개발 언어 : SWIFT


[소스 코드]

import UIKit

import Network

class ViewController: UIViewController {

    @IBOutlet weak var displayText: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        // [네트워크 연결 상태 활성 여부 체크 메소드 호출]
        checkNetworkStart()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        print("")
        print("===============================")
        print("[ViewController > viewDidAppear() : 뷰 화면 표시]")
        print("[네트워크 연결 상태 : \(String(self.checkNetworkValue))]")
        print("===============================")
        print("")
        
        if self.checkNetworkValue == true {
            showAlert(tittle: "네트워크 연결 상태", content: "연결", okBtb: "확인", noBtn: "")
        }
        else {
            showAlert(tittle: "네트워크 연결 상태", content: "비연결", okBtb: "확인", noBtn: "")
        }
    }

    /*
    [요약 설명]
    1. 필요 import : import Network
    2. NWPathMonitor : 내부 라이브러리로 네트워크 연결 상태를 확인할 수 있습니다
    3. 사용방법 : viewDidLoad()에서 checkNetworkStart() 메소드 호출 >> viewDidAppear() 에서 네트워크 연결상태 확인
    */
    let monitor = NWPathMonitor()
    var checkNetworkValue = false
    func checkNetworkStart() {
        self.monitor.start(queue: DispatchQueue.global())
        self.monitor.pathUpdateHandler = { path in
            if path.status == .satisfied { // 네트워크가 연결된 경우
                print("")
                print("===============================")
                print("[checkNetworkStart : Network Connected]")
                print("===============================")
                print("")
                if path.usesInterfaceType(.wifi) {
                    print("")
                    print("===============================")
                    print("[checkNetworkStart : Wifi Mode]")
                    print("===============================")
                    print("")
                }
                else if path.usesInterfaceType(.cellular) {
                    print("")
                    print("===============================")
                    print("[checkNetworkStart : Cellular Mode]")
                    print("===============================")
                    print("")
                }
                self.checkNetworkValue = true
            }
            else { // 네트워크가 연결되지 않은 경우
                print("")
                print("===============================")
                print("[checkNetworkStart : Network Not Connected]")
                print("===============================")
                print("")
                self.checkNetworkValue = false
            }
        }
    }
    func checkNetworkStop() {
        print("")
        print("===============================")
        print("[checkNetworkStop : end]")
        print("===============================")
        print("")
        self.monitor.cancel()
    }

    // [alert 팝업창 호출 메소드 정의 실시 : 이벤트 호출 시]
    // 호출 방법 : showAlert(tittle: "title", content: "content", okBtb: "확인", noBtn: "취소")
    func showAlert(tittle:String, content:String, okBtb:String, noBtn:String) {
        // [UIAlertController 객체 정의 실시]
        let alert = UIAlertController(title: tittle, message: content, preferredStyle: UIAlertController.Style.alert)
        
        // [인풋으로 들어온 확인 버튼이 nil 아닌 경우]
        if(okBtb != "" && okBtb.count>0){
            let okAction = UIAlertAction(title: okBtb, style: .default) { (action) in
                // [확인 버튼 클릭 이벤트 내용 정의 실시]
                return
            }
            alert.addAction(okAction) // 버튼 클릭 이벤트 객체 연결
        }
        
        // [인풋으로 들어온 취소 버튼이 nil 아닌 경우]
        if(noBtn != "" && noBtn.count>0){
            let noAction = UIAlertAction(title: noBtn, style: .default) { (action) in
                // [취소 버튼 클릭 이벤트 내용 정의 실시]
                return
            }
            alert.addAction(noAction) // 버튼 클릭 이벤트 객체 연결
        }
        
        // [alert 팝업창 활성 실시]
        present(alert, animated: false, completion: nil)
    }
    
}

 


[결과 출력]


 

반응형
Comments