Last active
May 9, 2022 00:58
-
-
Save yosshi4486/0ecfcfcf44c14b25a7cf1b7c0fd72d49 to your computer and use it in GitHub Desktop.
Sample use of NWPathMonitor
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
/// A class that checks and notifies an internect connectivity changes. | |
class NetworkConnectivityManager { | |
/// The static singleton instance. You can use this throught `NetworkConnectivityManager.shared`. | |
/// | |
/// Creating several manager instances doesn't make sense, so we design it as singleton. | |
static let shared = NetworkConnectivityManager() | |
/// The static notification name that the notification is post when a network status change. The object is [NWPath.Status](https://developer.apple.com/documentation/network/nwpath/status) | |
static let networkConnectivityDidChangeNotificationName = Notification.Name(rawValue: "_networkConnectivityDidChangeNotification") | |
/// The object that monitors the network path. | |
/// | |
/// You can check the current path status by `pathMonitor.currentPath.status`. | |
let pathMonitor = NWPathMonitor() | |
/// The queue for which enqueues network updates. | |
let monitoringQueue = DispatchQueue(label: "com.youDomain.NetworkConnectivityManager", qos: .utility) | |
/// The boolean value indicating whether the current network connection is online. | |
var isOnline: Bool { | |
return pathMonitor.currentPath.status == .satisfied | |
} | |
private init() { | |
pathMonitor.pathUpdateHandler = { path in | |
NotificationCenter.default.post(name: Self.networkConnectivityDidChangeNotificationName, object: path.status) | |
} | |
pathMonitor.start(queue: monitoringQueue) | |
} | |
deinit { | |
pathMonitor.cancel() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment