Skip to content

Instantly share code, notes, and snippets.

@hemangshah
Created April 15, 2018 08:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hemangshah/267743fd0dd474a5b668f69070d81d9e to your computer and use it in GitHub Desktop.
Save hemangshah/267743fd0dd474a5b668f69070d81d9e to your computer and use it in GitHub Desktop.
NetworkMonitor can be used to check for the Internet Connection
import UIKit
import Reachability
class NetworkMonitor {
static let shared = NetworkMonitor()
internal var isNetworkAvailable : Bool {
get {
return networkStatus != .none
}
}
fileprivate var networkStatus: Reachability.Connection = .none
fileprivate var reachability = Reachability()!
private init() {
config()
}
fileprivate func config() {
reachability.allowsCellularConnection = true
reachability.whenReachable = { reachability_block in
if reachability_block.connection == .cellular {
print("Network reachable through Cellular Data")
DispatchQueue.main.async {
self.networkStatus = .cellular
self.hideNoInternetConnectionTopAlert()
}
} else {
print("Network reachable through WiFi")
DispatchQueue.main.async {
self.networkStatus = .wifi
self.hideNoInternetConnectionTopAlert()
}
}
}
reachability.whenUnreachable = { _ in
print("Not reachable")
DispatchQueue.main.async {
self.networkStatus = .none
self.showNoInternetConnectionTopAlert()
}
}
}
fileprivate func showNoInternetConnectionTopAlert() {
let appDelegate = UIApplication.shared.delegate as? AppDelegate
appDelegate?.showNoInternetConnectionAlert()
}
fileprivate func hideNoInternetConnectionTopAlert() {
let appDelegate = UIApplication.shared.delegate as? AppDelegate
appDelegate?.hideNoInternetConnectionAlert()
}
// Starts monitoring network status
internal func startMonitoringNetwork() {
print("Network monitoring started")
do {
try self.reachability.startNotifier()
} catch {
print("Unable to start notifier")
}
}
// Stops monitoring network status
internal func stopMonitoringNetwork() {
print("Network monitoring stopped")
self.reachability.stopNotifier()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment