Created
April 15, 2018 08:17
-
-
Save hemangshah/267743fd0dd474a5b668f69070d81d9e to your computer and use it in GitHub Desktop.
NetworkMonitor can be used to check for the Internet Connection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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