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

你可能感兴趣的:(Swift 网络实时监测类)