Home > AI > IOS > Network >

NWPathMonitor

Example :


import SwiftUI
import Network


struct ContentView: View {
    @EnvironmentObject var network: NetworkMonitor

    var body: some View {
        
        VStack {
            Button("Fetch Data", action: makeRequest)
        }
        
        Text(verbatim: """
        Active: \(network.isActive)
        Expensive: \(network.isExpensive)
        Constrained: \(network.isConstrained)
        """)
    }
    
    
    func makeRequest() {
        let config = URLSessionConfiguration.default
        config.allowsExpensiveNetworkAccess = false
        config.allowsConstrainedNetworkAccess = false

        let session = URLSession(configuration: config)
        let url = URL(string: "https://www.apple.com")!

        session.dataTask(with: url) { data, response, error in
            print(data ?? "")
        }.resume()
    }
}




class NetworkMonitor: ObservableObject {
    var isActive = false // do we have access to the network?
    var isExpensive = false // cellular or WiFi using a cellular hotspot
    var isConstrained = false // restricted by low data mode
    var connectionType = NWInterface.InterfaceType.other // WiFi, cellular, etc
    
    
    private let monitor = NWPathMonitor()
    private let queue = DispatchQueue(label: "Monitor")
    
    
    init() {
        monitor.pathUpdateHandler = { path in
            
            // more code here
            self.isActive = path.status == .satisfied
            self.isExpensive = path.isExpensive
            self.isConstrained = path.isConstrained

            let connectionTypes: [NWInterface.InterfaceType] = [.cellular, .wifi, .wiredEthernet]
            self.connectionType = connectionTypes.first(where: path.usesInterfaceType) ?? .other

            DispatchQueue.main.async {
                self.objectWillChange.send()
            }
        }

        monitor.start(queue: queue)
    }
    
}

Related posts:
    No posts found.

Leave a Reply