Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import UIKit
- import Alamofire
- enum ReachabilityManagerError: Error {
- case notReachable
- }
- struct ReachabilityManager {
- /// singleton
- static let `default` : ReachabilityManager = {
- let manager = ReachabilityManager()
- // configuration
- return manager
- }()
- /// Alamofire (NetworkReachabilityManager)
- let networkManager = NetworkReachabilityManager()!
- /// key to send notification by changing the status of the network
- let listenerNetworkStatusChanged = NSNotification.Name(rawValue:"NSNotificationKeyListenerNetworkStatusChanged")
- //MARK:-
- //MARK: check network
- /// check internet connection
- ///
- /// - returns: network status
- func checkInternetConnection() -> Bool {
- switch networkManager.networkReachabilityStatus {
- case NetworkReachabilityManager.NetworkReachabilityStatus.notReachable, NetworkReachabilityManager.NetworkReachabilityStatus.unknown:
- return false
- default:
- return true
- }
- }
- /// check internet connection (throws)
- ///
- /// - throws: in the absence of network
- func checkConnection() throws {
- switch networkManager.networkReachabilityStatus {
- case NetworkReachabilityManager.NetworkReachabilityStatus.notReachable,
- NetworkReachabilityManager.NetworkReachabilityStatus.unknown:
- throw ReachabilityManagerError.notReachable
- default: return
- }
- }
- //MARK:-
- //MARK: listening
- /// start
- ///
- func startNetworkListening() {
- networkManager.listener = { status in
- /// - unknown: It is unknown whether the network is reachable.
- /// - notReachable: The network is not reachable.
- /// - reachable: The network is reachable.
- NotificationCenter.default.post(name: self.listenerNetworkStatusChanged,
- object: nil,
- userInfo: ["NetworkStatus": status])
- }
- networkManager.startListening()
- }
- /// stop
- ///
- func stopNetworkListening() {
- networkManager.stopListening()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement