ContentView.swift
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | // // ContentView.swift // Test // // Created by Cairocoders // import SwiftUI struct ContentView: View { @ObservedObject var monitor = NetworkMonitor() @State private var showAlertSheet = false var body: some View { VStack { Image(systemName: monitor.isConnected ? "wifi" : "wifi.slash" ) .font(. system (size: 56)) Text(monitor.isConnected ? "Connected!" : "Not connected!" ) .padding() Button( "Perform Network Request" ) { self.showAlertSheet = true } } .alert(isPresented: $showAlertSheet, content: { if monitor.isConnected { return Alert(title: Text( "Success!" ), message: Text( "The network request can be performed" ), dismissButton: . default (Text( "OK" ))) } return Alert(title: Text( "No Internet Connection" ), message: Text( "Please enable Wifi or Celluar data" ), dismissButton: . default (Text( "Cancel" ))) }) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | // // NetworkMonitor.swift // Test // // Created by Cairocoders // import Foundation import Network final class NetworkMonitor: ObservableObject { let monitor = NWPathMonitor() let queue = DispatchQueue(label: "Monitor" ) @Published var isConnected = true init() { monitor.pathUpdateHandler = { [weak self] path in DispatchQueue.main.async { self?.isConnected = path.status == .satisfied ? true : false } } monitor.start(queue: queue) } } |