Swift 網絡實時監測類

//
//  MCReachabilityManager.swift
//  MCBaseModule
//
//  Created by 優優 on 2022/8/9.
//  Copyright ? 2022 MIXC. All rights reserved.
//

import UIKit
import Reachability

public enum ReachabilityStatus {
   case notReachable
   case unknown
   case ethernetOrWiFi
   case wwan
}

public class MCReachabilityManager: NSObject {

    public static let shared = MCReachabilityManager()
    fileprivate var reachability: Reachability?

    public typealias NetworkReachable = (ReachabilityStatus) -> Void
    public typealias NetworkUnreachable = (ReachabilityStatus) -> Void

    public var whenReachable: NetworkReachable? // 網絡連接回調(實時)
    public var whenUnreachable: NetworkUnreachable? // 網絡斷開回調(實時)

    private  override init() {
        super.init()
    }

    /// 是否聯網 (這一刻)
    public var isReachable: Bool {
        get {
            guard let reachability = try? Reachability() else { return false }
            if reachability.connection == .wifi || reachability.connection == .cellular {
                return true
            }
            return false
        }
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    /// 網絡監聽
    public func startListening() {
        guard let reachability = try? Reachability() else { return }
        self.reachability = reachability
        NotificationCenter.default.addObserver(self, selector: #selector(MCReachabilityManager.reachabilityChanged(_:)), name: .reachabilityChanged, object: reachability)
        do {
            try reachability.startNotifier()
        } catch {

        }
    }

   @objc func reachabilityChanged(_ note: Notification) {

       guard let reachability = note.object as? Reachability else { return }

       switch reachability.connection {
       case .wifi:
           whenReachable?(.ethernetOrWiFi)
       case .cellular:
           whenReachable?(.wwan)
       case .none:
           whenUnreachable?(.unknown)
       case .unavailable:
           whenUnreachable?(.unknown)
       }
   }

    deinit {
        self.reachability?.stopNotifier()
    }
}

使用:
在delegate里添加全局監聽

// 添加網絡監聽
        MCReachabilityManager.shared.startListening()
        // 實時監聽聯網
        MCReachabilityManager.shared.whenReachable = { _ in
            if MCAppUpdataService.shared.newVersion.isEmpty {
                // 獲取更新信息
                MCAppUpdataService.shared.checkNeedUpdata()
            }
        }
image.png
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容