Created
February 19, 2019 10:13
-
-
Save Nexengineer/a57cd4b3b56eafdc9a12faedbed61000 to your computer and use it in GitHub Desktop.
Network avaliablity
This file contains 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
// | |
// NetworkManager.swift | |
// Xaas | |
// | |
// Created by Neeraj K Mishra on 07/01/19. | |
// Copyright © 2019 PwC. All rights reserved. | |
// | |
import Foundation | |
import Reachability | |
class NetworkManager: NSObject { | |
var reachability: Reachability! | |
// Create a singleton instance | |
static let sharedInstance: NetworkManager = { return NetworkManager() }() | |
override init() { | |
super.init() | |
// Initialise reachability | |
reachability = Reachability()! | |
// Register an observer for the network status | |
NotificationCenter.default.addObserver( | |
self, | |
selector: #selector(networkStatusChanged(_:)), | |
name: .reachabilityChanged, | |
object: reachability | |
) | |
do { | |
// Start the network status notifier | |
try reachability.startNotifier() | |
} catch { | |
print("Unable to start notifier") | |
} | |
} | |
@objc func networkStatusChanged(_ notification: Notification) { | |
// Do something globally here! | |
} | |
static func stopNotifier() -> Void { | |
do { | |
// Stop the network status notifier | |
try (NetworkManager.sharedInstance.reachability).startNotifier() | |
} catch { | |
print("Error stopping notifier") | |
} | |
} | |
// Network is reachable | |
static func isReachable(completed: @escaping (NetworkManager) -> Void) { | |
if (NetworkManager.sharedInstance.reachability).connection != .none { | |
completed(NetworkManager.sharedInstance) | |
} | |
} | |
// Network is unreachable | |
static func isUnreachable(completed: @escaping (NetworkManager) -> Void) { | |
if (NetworkManager.sharedInstance.reachability).connection == .none { | |
completed(NetworkManager.sharedInstance) | |
} | |
} | |
// Network is reachable via WWAN/Cellular | |
static func isReachableViaWWAN(completed: @escaping (NetworkManager) -> Void) { | |
if (NetworkManager.sharedInstance.reachability).connection == .cellular { | |
completed(NetworkManager.sharedInstance) | |
} | |
} | |
// Network is reachable via WiFi | |
static func isReachableViaWiFi(completed: @escaping (NetworkManager) -> Void) { | |
if (NetworkManager.sharedInstance.reachability).connection == .wifi { | |
completed(NetworkManager.sharedInstance) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment