Network connectivity should come only when changed

Viewed 213

I am using Alamofire NetworkReachabilityManager for managing my connections like below.

    let reachabilityManager = NetworkReachabilityManager()
   reachabilityManager?.listener = { [weak self] status in
            switch status {
            case .notReachable:
                self?.connectionType = .notReachable
                break
            case .unknown:
                self?.connectionType = .notReachable
                break
            case .reachable(.ethernetOrWiFi):
                self?.connectionType = .wifi
                break
            case .reachable(.wwan):
                self?.connectionType = .cellular

                break
            }

public enum ReachabilityStatus {
    case unknown
    case notReachable
    case wifi
    case cellular
}

I am getting this callback when i am launching the application itself but I don't want this callback I need callback only when there is a change in network connection.

How can I solve this?

2 Answers

What about creating a variable to store the previous state and checking if the variable is nil on the first call. After that you can always check if the state has changed.

let reachabilityManager = NetworkReachabilityManager()
var previousStatus: ReachabilityStatus? = nil

reachabilityManager?.listener = { [weak self] status in

    if let p = self.previousStatus, p == status {
        return // status hasn't changed
    } else {
        // status is nil
        self.previousStatus = status
        return 
    }

    switch status {
    case .notReachable:
        self?.connectionType = .notReachable
        break
    case .unknown:
        self?.connectionType = .notReachable
        break
    case .reachable(.ethernetOrWiFi):
        self?.connectionType = .wifi
        break
    case .reachable(.wwan):
        self?.connectionType = .cellular

        break
}

You can add listener after some delay. so listener should be nil when NetworkReachabilityManager gets instantiated on app launch

    let reachabilityManager = NetworkReachabilityManager()
    var previousStatus: ReachabilityStatus? = nil

    DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
    reachabilityManager?.listener = { [weak self] status in

    if let p = self.previousStatus, p == status {
        return // status hasn't changed
    } else {
        // status is nil
        self.previousStatus = status
        return 
    }

    switch status {
    case .notReachable:
        self?.connectionType = .notReachable
        break
    case .unknown:
        self?.connectionType = .notReachable
        break
    case .reachable(.ethernetOrWiFi):
        self?.connectionType = .wifi
        break
    case .reachable(.wwan):
        self?.connectionType = .cellular

        break
 }
})

Edit: i have tested this code. it works.

Related