Check for internet connection with Swift

前端 未结 21 1822
别跟我提以往
别跟我提以往 2020-11-22 05:59

When I try to check for an internet connection on my iPhone I get a bunch of errors. Can anyone help me to fix this?

The code:

import Foundation
impo         


        
21条回答
  •  春和景丽
    2020-11-22 06:15

    if your project has a target above or equal iOS 12 and uses combine you could use this little piece of code.

    import Combine
    import Network
    
    enum NerworkType {
        case wifi
        case cellular
        case loopBack
        case wired
        case other
    }
    
    protocol ReachabilityServiceContract {
        var reachabilityInfos: PassthroughSubject { get set }
        var isNetworkAvailable: CurrentValueSubject { get set }
        var typeOfCurrentConnection: PassthroughSubject { get set }
    }
    
    final class ReachabilityService: ReachabilityServiceContract {
        var reachabilityInfos: PassthroughSubject = .init()
        var isNetworkAvailable: CurrentValueSubject = .init(false)
        var typeOfCurrentConnection: PassthroughSubject = .init()
    
        private let monitor: NWPathMonitor
        private let backgroudQueue = DispatchQueue.global(qos: .background)
    
        init() {
            monitor = NWPathMonitor()
            setUp()
        }
    
        init(with interFaceType: NWInterface.InterfaceType) {
            monitor = NWPathMonitor(requiredInterfaceType: interFaceType)
            setUp()
        }
    
        deinit {
            monitor.cancel()
        }
    }
    
    private extension ReachabilityService {
        func setUp() {
        
            monitor.pathUpdateHandler = { [weak self] path in
                self?.reachabilityInfos.send(path)
                switch path.status {
                case .satisfied:
                    self?.isNetworkAvailable.send(true)
                case .unsatisfied, .requiresConnection:
                    self?.isNetworkAvailable.send(false)
                @unknown default:
                    self?.isNetworkAvailable.send(false)
                }
                if path.usesInterfaceType(.wifi) {
                    self?.typeOfCurrentConnection.send(.wifi)
                } else if path.usesInterfaceType(.cellular) {
                    self?.typeOfCurrentConnection.send(.cellular)
                } else if path.usesInterfaceType(.loopback) {
                    self?.typeOfCurrentConnection.send(.loopBack)
                } else if path.usesInterfaceType(.wiredEthernet) {
                    self?.typeOfCurrentConnection.send(.wired)
                } else if path.usesInterfaceType(.other) {
                    self?.typeOfCurrentConnection.send(.other)
                }
            }
        
            monitor.start(queue: backgroudQueue)
        }
    }
    

    Just subscribe to the variable you want to follow and you should be updated of any changes.

提交回复
热议问题