//
// 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