Created
October 3, 2024 12:56
-
-
Save awaismubeen/f10f47915833cf52413f40ac2a8211ed to your computer and use it in GitHub Desktop.
This class is used to check the connectivity a MAC OSX project
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
extension Notification.Name{ | |
static let internetIsBack = Notification.Name(rawValue: "internetIsBack") | |
} | |
class ReachabilityManager:NSObject { | |
private var monitor: NWPathMonitor? | |
private var queue = DispatchQueue.global(qos: .background) | |
private var isConnected: Bool = false // To store the current network status | |
static let shared:ReachabilityManager = ReachabilityManager()// Singleton instance for global access | |
override init() { | |
super.init() | |
startMonitoring() // Automatically start monitoring when NetworkManager is initialized | |
} | |
// Start monitoring the network connection | |
func startMonitoring() { | |
monitor = NWPathMonitor() | |
monitor?.start(queue: queue) | |
monitor?.pathUpdateHandler = { [weak self] path in | |
guard let self = self else { return } | |
if path.status == .satisfied { | |
self.isConnected = true | |
print("Connected to the network.") | |
NotificationCenter.default.post(name: .internetIsBack, object: nil) | |
} else { | |
self.isConnected = false | |
print("No network connection.") | |
} | |
} | |
} | |
// Stop monitoring the network connection | |
func stopMonitoring() { | |
monitor?.cancel() | |
monitor = nil | |
} | |
// Method to check if the network is currently available | |
func isNetworkReachable() -> Bool { | |
return isConnected | |
} | |
// Method to show an alert when network is not available | |
func showNetworkError(){ | |
let alert = NSAlert() | |
alert.messageText = "Network Unavailable" | |
alert.informativeText = "It seems you are not connected to the internet. Please check your connection." | |
alert.alertStyle = .warning | |
alert.addButton(withTitle: "OK") | |
if let window = NSApplication.shared.windows.first { | |
alert.beginSheetModal(for: window) { response in | |
// Handle response if necessary | |
} | |
} else { | |
alert.runModal() // Use runModal if no window is present | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment