Skip to content

Instantly share code, notes, and snippets.

@saamerm
Created March 26, 2024 18:47
Show Gist options
  • Save saamerm/9fe10c40466b8b1c59977b05cff6565c to your computer and use it in GitHub Desktop.
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
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