Skip to content

Instantly share code, notes, and snippets.

@vdeep
Last active January 2, 2018 07:49
Show Gist options
  • Save vdeep/3865062e854982bcd55076e25298e225 to your computer and use it in GitHub Desktop.
Save vdeep/3865062e854982bcd55076e25298e225 to your computer and use it in GitHub Desktop.
ReachabilityManager - Using https://github.com/ashleymills/Reachability.swift, updated for Swift 4.2
import Foundation
import Reachability
class ReachabilityManager: NSObject {
static let shared = ReachabilityManager()
var isNetworkAvailable: Bool {
return reachabilityStatus != .none
}
var reachabilityStatus: Reachability.Connection = .none
let reachability = Reachability()
@objc func reachabilityChanged(_ notification: Notification) {
if let reachability = notification.object as? Reachability {
switch reachability.connection {
case .none:
debugPrint("Network became unreachable")
case .wifi:
debugPrint("Network reachable through WiFi")
case .cellular:
debugPrint("Network reachable through Cellular Data")
}
} else {
debugPrint("ReachabilityManager - Unrecognized notification object")
}
}
func startMonitoring() {
NotificationCenter.default.addObserver(self,
selector: #selector(reachabilityChanged(_:)),
name: Notification.Name.reachabilityChanged,
object: reachability)
do {
try reachability?.startNotifier()
} catch {
debugPrint("Could not start reachability notifier")
}
}
func stopMonitoring() {
reachability?.stopNotifier()
NotificationCenter.default.removeObserver(self, name: Notification.Name.reachabilityChanged,
object: reachability)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment