Created
March 26, 2024 18:47
-
-
Save saamerm/9fe10c40466b8b1c59977b05cff6565c to your computer and use it in GitHub Desktop.
An Internet Connectivity class in swift language, to add a check to see if the device is connected to the internet, and an example of how it is implemented in SwiftUI
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 | |
class NetworkMonitor: ObservableObject { | |
@Published var isInternetAvailable = false | |
init() { | |
startMonitoring() | |
} | |
func startMonitoring() { | |
let monitor = NWPathMonitor() | |
monitor.pathUpdateHandler = { path in | |
DispatchQueue.main.async { | |
self.isInternetAvailable = path.status == .satisfied | |
} | |
} | |
let queue = DispatchQueue(label: "Monitor") | |
monitor.start(queue: queue) | |
} | |
} | |
// -------------- You can put these in separate files generally and ContentView is just any sample view | |
struct ContentView: View { // | |
@StateObject var networkMonitor = NetworkMonitor() | |
var body: some View { | |
} | |
.onReceive(networkMonitor.$isInternetAvailable, perform: { isInternetAvailable in | |
if isInternetAvailable { | |
//DO WORK | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment