Skip to content

Monitoring iOS device's network connectivity using Apple's Network framework

License

Notifications You must be signed in to change notification settings

aresxin/NWReachability

Repository files navigation

NWReachability

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

Installation

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. To install NWReachability with CocoaPods:

  1. Make sure CocoaPods is installed.

  2. 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
  3. Run pod install.

  1. In your code import NWReachability like so:
    import NWReachability
    import Combine

Swift Package Manager

  • File > Swift Packages > Add Package Dependency
  • Add https://github.com/aresxin/NWReachability.git
  • Select "Up to Next Major" with "1.1.1"

Usage

Example - notifications

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)

Example - Combine

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()

About

Monitoring iOS device's network connectivity using Apple's Network framework

Resources

License

Stars

Watchers

Forks

Packages

No packages published