Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AFNetworking 5 - NetworkReachabilityManager Listener

I recently upgraded from AFNetworking 4 to 5.

This was the old way of initializing the listener:

let net = NetworkReachabilityManager()

net?.listener = { status in
if net?.isReachable ?? false {

switch status {

    case .reachable(.ethernetOrWiFi):
        print("The network is reachable over the WiFi connection")

    case .reachable(.wwan):
        print("The network is reachable over the WWAN connection")

    case .notReachable:
        print("The network is not reachable")

    case .unknown :
        print("It is unknown whether the network is reachable")

    }
}

net?.startListening()

The new documentation reads this:

@discardableResult
open func startListening(onQueue queue: DispatchQueue = .main,
                         onUpdatePerforming listener: @escaping Listener) -> Bool

https://alamofire.github.io/Alamofire/Classes/NetworkReachabilityManager.html

In my code, I am trying this:

let listener = NetworkReachabilityManager.Listener()

self.reachabilityManager?.startListening(onUpdatePerforming: listener){


}

The compilation error I am getting is Extra argument 'onUpdatePerforming' in call. It is a syntactical issue, I am transitioning form Objective C to Swift.

What I attempt to pass a closure, I also cannot seem to get the syntax correct:

   self.reachabilityManager?.startListening(onUpdatePerforming: { (NetworkReachabilityManager.Listener) in


    })
like image 378
stackOverFlew Avatar asked Sep 07 '25 15:09

stackOverFlew


2 Answers

Listener is just a typealias for the closure type expected, so you need to pass a closure.

self.reachabilityManager?.startListening { status in
    switch status {
    ...
    }
}
like image 94
Jon Shier Avatar answered Sep 09 '25 03:09

Jon Shier


Here is the code which runs after the AFNetworking update:

    self.reachabilityManager?.startListening(onUpdatePerforming: {networkStatusListener in

        print("Network Status Changed:", networkStatusListener)

           switch networkStatusListener {
           case .notReachable:
               self.presentAlert(message: "The network is not reachable. Please reconnect to continue using the app.")
                       print("The network is not reachable.")
               case .unknown :
                       self.presentAlert(message: "It is unknown whether the network is reachable. Please reconnect.")
                       print("It is unknown whether the network is reachable.")
               case .reachable(.ethernetOrWiFi):
                       print("The network is reachable over the WiFi connection")

               case .reachable(.cellular):
                       print("The network is reachable over the WWAN connection")
        }

    })
like image 29
stackOverFlew Avatar answered Sep 09 '25 04:09

stackOverFlew