NWReachability is a pure Swift library for monitoring the network connection of iOS devices using Apple's Network framework.
-
Latest release: version 1.1.1
-
Requirements: iOS 13.0~ / Swift 5.0~
-
Combine Support
CocoaPods is a dependency manager for Cocoa projects. To install NWReachability with CocoaPods:
-
Make sure CocoaPods is installed.
-
Update your Podfile to include the following:
source 'https://github.com/CocoaPods/Specs.git' platform :ios, '13.0' use_frameworks! target 'YourApp' do # your other pod # ... pod 'NWReachability', '~> 1.1.0' end
-
Run
pod install
.
- In your code import NWReachability like so:
import NWReachability
import Combine
- File > Swift Packages > Add Package Dependency
- Add
https://github.com/aresxin/NWReachability.git
- Select "Up to Next Major" with "1.1.1"
NOTE: All notifications are delivered on the main queue.
let token = NWReachability.default.addObserver { [weak self] connectivity in
print("connectivity isConnected \(connectivity.isConnected)")
print("connectivity isExpensive \(connectivity.isExpensive)")
switch connectivity.status {
case .reachable(.cellular):
print("cellular")
case .notReachable:
print("notReachable")
case .reachable(.ethernetOrWiFi):
print("ethernetOrWiFi")
case .unknown:
print("unknown")
}
}
NWReachability.default.startMonitoring()
and for stopping notifications
NWReachability.default.stopMonitoring()
NotificationCenter.default.removeObserver(token as Any)
NWReachability.default.publisher.sink { [weak self] connectivity in
print("connectivity isConnected \(connectivity.isConnected)")
print("connectivity isExpensive \(connectivity.isExpensive)")
switch connectivity.status {
case .reachable(.cellular):
print("cellular")
case .notReachable:
print("notReachable")
case .reachable(.ethernetOrWiFi):
print("ethernetOrWiFi")
case .unknown:
print("unknown")
}
}.store(in: &cancellables)
NWReachability.default.startMonitoring()
and for stopping
NWReachability.default.stopMonitoring()
cancellables.removeAll()