Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • NetworkReachability Listener in Alamofire

    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 3.99k
    Comment on it

    Alamofire provides a method to check network status reachable on WWAN, Ethernet and wifi. The NetworkReachabilityManager class provided by Alamofire listens whenever there is a change in network.

    It can be used to determine background information and reasons why a network operation failed and retries network requests when a connection is established. We can use reachability listeners to perform background tasks whenever a network is reachable.

     

    Here are steps to start network reachability listener:

    1- Initialise NetworkReachabilityManager with a host to evaluate network; Here we are using www.google.com for now, you can use your own.

    let manager = NetworkReachabilityManager(host: "www.google.com")

            
    2 A closure to be executed when there is a change in network status.

     manager?.listener = { status in
                
                	print("Network Status Changed: \(status)")
                	print("network reachable \(manager!.isReachable)")
    				                print(You can do your code here)
            }

     

    3- Start listening the network change.

    manager?.startListening()
    
    	startlistening method will start looking for changes in network status.
    

     

    To stop the listener use method below:

    manager?.stopListening()

    ‘stopListening’ method will stop looking for changes in network status. Here ‘manager’ is NetworkReachabilityManager objects initialised in 1st step.

     

    Code Snippet:

    let manager = NetworkReachabilityManager(host: "www.google.com")
    manager?.listener = { status in
                
                print("Network Status Changed: \(status)")
                print("network reachable \(manager!.isReachable)")
            }
     manager?.startListening()

     

 1 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: