Last active
August 31, 2019 22:51
-
-
Save LukeSmith16/7263da935602bfe81cc7679c9414f018 to your computer and use it in GitHub Desktop.
NetworkStatus - Monitor the network connection and subscribe for connectivity changes, uses the Network framework. I still don't think this is a perfect implementation to achieve this sort of behaviour but it's not too bad.
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
import Network | |
protocol NetworkStatusChangedDelegate { | |
func networkStatusChanged(_ status: NetworkConnection) | |
} | |
enum NetworkConnection { | |
case Connected | |
case Disconnected | |
} | |
struct NetworkStatus { | |
static let shared = NetworkStatus() | |
private static let delegates = MulticastDelegate<NetworkStatusChangedDelegate>() | |
private static let monitor: NWPathMonitor = { | |
let monitor = NWPathMonitor() | |
monitor.pathUpdateHandler = { path in | |
delegates.invoke({ (delegate) in | |
switch path.status { | |
case .satisfied: | |
delegate.networkStatusChanged(.Connected) | |
default: | |
delegate.networkStatusChanged(.Disconnected) | |
} | |
}) | |
} | |
return monitor | |
}() | |
private init() { | |
fatalError("NetworkStatus shouldn't be instantiated access it via 'NetworkStatus.shared'") | |
} | |
public static func getNetworkStatus() -> NetworkConnection { | |
switch monitor.currentPath.status { | |
case .satisfied: | |
return .Connected | |
default: | |
return .Disconnected | |
} | |
} | |
public static func addNetworkObserver(_ observer: NetworkStatusChangedDelegate) { | |
delegates.add(observer) | |
} | |
public static func removeNetworkObserver(_ observer: NetworkStatusChangedDelegate) { | |
delegates.remove(observer) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment