NetworkDetector is a very simple library for iOS, macOS, and tvOS that detects network changes and calls a closure or broadcasts a notification based on the network status. NetworkDetector uses NWPathMonitor under the hood that introduced in iOS 12 and aims to eliminate the usage of Reachability class used for so many years. The library is inspired by Ashley Mills' Reachability.swift, so the usage is similar even though it uses NWPathMonitor under the hood.
NetworkDetector is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'NetworkDetector'
Example projects for iOS, macOS, and tvOS are included with this repo. To run the example projects, clone the repo, and run pod install
from the Example directory first.
NOTE: All closures are run on the main queue.
//declare this property where it won't go out of scope relative to your listener
let networkDetector = NetworkDetector()
networkDetector.reachableHandler = {
print("Internet connection is active")
}
networkDetector.unreachableHandler = {
print("Internet connection is down")
}
do {
try networkDetector.startMonitoring()
} catch let error {
print(error.localizedDescription)
}
and for stopping monitoring
networkDetector.stopMonitoring()
NOTE: All notifications are delivered on the main queue.
//declare this property where it won't go out of scope relative to your listener
let networkDetector = NetworkDetector()
NotificationCenter.default.addObserver(self, selector: #selector(networkStatusChanged(_:)), name: .networkStatusChanged, object: networkDetector)
do {
try networkDetector.startMonitoring()
} catch let error {
print(error.localizedDescription)
}
and
@objc private func networkStatusChanged(_ note: Notification) {
let networkDetector = note.object as! NetworkDetector
switch networkDetector.connection {
case .reachable:
print("The network is reachable")
case .none:
print("Network not reachable")
}
}
and for stopping monitoring
networkDetector.stopMonitoring()
- iOS 12.0+ / macOS 10.14+ / tvOS 12.0+
- Xcode 10.1+
- Swift 4.2+
Got a bug fix, or a new feature? You are more than welcome to create a pull request.
Spyros Zarzonis, [email protected]
NetworkDetector is available under the MIT license. See the LICENSE file for more info.