Repository for project of Medium Blog Network reachability status monitoring on iOS (Part 2)
- Install ReachibilitySwift with
pod ‘ReachabilitySwift’, ‘~> 3’
withcocoapods
- Drag and Drop
ReachabilityManager.swift
to your project from...NetworkStatusMonitorPart1/NetworkStatusMonitor/Networking/Core
Override AppDelegate
's func applicationDidBecomeActive(_:)
func applicationDidBecomeActive(_ application: UIApplication) {
// Starts monitoring network reachability status changes
ReachabilityManager.shared.startMonitoring()
}
Override AppDelegate
's func applicationWillEnterForeground(_:)
func applicationWillEnterForeground(_ application: UIApplication) {
// Stops monitoring network reachability status changes
ReachabilityManager.shared.stopMonitoring()
}
1. Implement `NetworkStatusListener` in `ViewController` class
extension ViewController: NetworkStatusListener {
func networkStatusDidChange(status: Reachability.NetworkStatus) {
switch status {
case .notReachable:
debugPrint("ViewController: Network became unreachable")
case .reachableViaWiFi:
debugPrint("ViewController: Network reachable through WiFi")
case .reachableViaWWAN:
debugPrint("ViewController: Network reachable through Cellular Data")
}
// Take necessary actions here
}
}
2. Override `viewWillAppear(_:)` and `viewDidDisappear(_:)`
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
ReachabilityManager.shared.addListener(listener: self)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
ReachabilityManager.shared.removeListener(listener: self)
}