Skip to content

A simple iOS library written in Swift that detects network changes

License

Notifications You must be signed in to change notification settings

musa-almatri/NetworkDetector

 
 

Repository files navigation

NetworkDetector

Version License Platform

Description

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.

Installation

NetworkDetector is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'NetworkDetector'

Example

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.

Usage

Closures

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

Notifications

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

Requirements

  • iOS 12.0+ / macOS 10.14+ / tvOS 12.0+
  • Xcode 10.1+
  • Swift 4.2+

Want to help?

Got a bug fix, or a new feature? You are more than welcome to create a pull request.

Author

Spyros Zarzonis, [email protected]

License

NetworkDetector is available under the MIT license. See the LICENSE file for more info.

About

A simple iOS library written in Swift that detects network changes

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Swift 82.0%
  • Ruby 18.0%