pod 'RealReachability'
// 封装
import UIKit
import RealReachability
protocol LCZRealStatusDelegate {
/// 未知网络
func LCZRealStatusUnknown();
/// 无网络
func LCZRealStatusNotReachable();
/// 4G
func LCZRealStatusViaWWAN();
/// WIFI
func LCZRealStatusViaWiFi();
}
class LCZRealReachabilityTool {
static let shared = LCZRealReachabilityTool()
public var delegate: LCZRealStatusDelegate?
private init() {}
/// 实时检测网络状态
func realTimeMonitorNetworkStatus() {
let realReachability = RealReachability.sharedInstance()
realReachability?.startNotifier()
NotificationCenter.default.addObserver(self, selector: #selector(networkChanged(notification:)), name: NSNotification.Name("kRealReachabilityChangedNotification"), object: nil)
// 首次监测网络状态
networkState(realReachability!)
}
@objc private func networkChanged(notification: NSNotification) {
let realReachability = notification.object as! RealReachability;
networkState(realReachability)
}
private func networkState(_ realReachability: RealReachability) {
realReachability.reachability { (state) in
switch state {
case .RealStatusUnknown:
self.delegate?.LCZRealStatusUnknown()
break;
case .RealStatusNotReachable:
self.delegate?.LCZRealStatusNotReachable()
break;
case .RealStatusViaWWAN:
self.delegate?.LCZRealStatusViaWWAN()
break;
case .RealStatusViaWiFi:
self.delegate?.LCZRealStatusViaWiFi()
break;
}
}
}
}
extension AppDelegate {
/// 开启实时检测网络状态
func startRealTimeMonitorNetworkStatus() {
let lczRealReachabilityTool = LCZRealReachabilityTool.shared
lczRealReachabilityTool.realTimeMonitorNetworkStatus()
}
}
// 使用
// 1. AppDelegate
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// 开启实时检测网络状态
startRealTimeMonitorNetworkStatus()
return true
}
// 2. ViewController
import UIKit
class ViewController: LCZBaseViewController,LCZRealStatusDelegate {
// 必须写在这里
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let lcz = LCZRealReachabilityTool.shared
lcz.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
}
// 实现代理方法
func LCZRealStatusUnknown() {
LCZSVProgressHUDTool.dismiss()
LCZSVProgressHUDTool.show(title: "LCZRealStatusUnknown")
}
func LCZRealStatusNotReachable() {
LCZSVProgressHUDTool.dismiss()
LCZSVProgressHUDTool.show(title: "LCZRealStatusNotReachable")
}
func LCZRealStatusViaWWAN() {
LCZSVProgressHUDTool.dismiss()
LCZSVProgressHUDTool.show(title: "LCZRealStatusViaWWAN")
}
func LCZRealStatusViaWiFi() {
LCZSVProgressHUDTool.dismiss()
LCZSVProgressHUDTool.show(title: "LCZRealStatusViaWiFi")
}
网友评论