7

In my app I have to alert whenever a network change happens for example when a app is connected or disconnected or changed(wifi to data) network.

But finding it by reaching a url seems expensive.

Is there any public api available in iOS to do this.

4 Answers4

5

I followed this tutorial

https://www.youtube.com/watch?v=wDZmz9IsB-8

credit --> Vasil Nunev

Download this class and import to my project --> Reachability.swift

https://github.com/ashleymills/Reachability.swift

(Reachability.swift) --> Unzip -->Sources/Reachability.swift

This is my view controller

import UIKit

class ViewController: UIViewController {

let reachability =  Reachability()!

override func viewDidLoad() {
    super.viewDidLoad()

    reachability.whenReachable = { _ in
        DispatchQueue.main.async {
            self.view.backgroundColor = UIColor.green
        }
    }

    reachability.whenUnreachable = { _ in
        DispatchQueue.main.async {
            self.view.backgroundColor = UIColor.red
        }
    }

    NotificationCenter.default.addObserver(self, selector: #selector(internetChanged), name: Notification.Name.reachabilityChanged , object: reachability)
    do{
        try reachability.startNotifier()
    } catch {
        print("Could not strat notifier")
    }
}

@objc  func internetChanged(note:Notification)  {
    let reachability  =  note.object as! Reachability
    if reachability.isReachable{
        if reachability.isReachableViaWiFi{
            self.view.backgroundColor = UIColor.green
        }
        else{
            DispatchQueue.main.async {
                self.view.backgroundColor = UIColor.orange
            }
        }
    } else{
        DispatchQueue.main.async {
            self.view.backgroundColor = UIColor.red
        }
    }
}
}
user3826696
  • 1,045
  • 12
  • 13
  • In your implementation you'll get 2 notifications each time the state changes. 1 in the Reachability callbacks and 1 in the internetChanged() – Nativ Nov 04 '18 at 10:39
3

Look at this official Apple documentation

Using Reachability you can recognize the type of your connection.

There is also a complete example on how detect the changes and the documentation is updated now for ARC.

I hope this can help you

Lorenzo
  • 3,293
  • 4
  • 29
  • 56
  • 1
    Can reachability detect type of a connection like wifi or vpn or data card etc like that meta datas.. – sathishkumar_kingmaker Oct 05 '15 at 14:30
  • Only if you are connected in wi-fi, cellular network, and if you are connected to internet. I don't remember if you have also information about vpn nut I think you can check it. – Lorenzo Oct 05 '15 at 14:34
  • Download the example, it is very easy to understand... you can run directly in the simulator or in the phone . The code is small.. – Lorenzo Oct 05 '15 at 14:37
0

Possible help:

Community
  • 1
  • 1
Sergei Stralenia
  • 855
  • 7
  • 16
0

If you're using Alamofire in your application, you can use it's NetworkReachabilityManager.swift class to listen for network's connectivity.

This is the piece of code.

@discardableResult
open func startListening(onQueue queue: DispatchQueue = .main,
                             onUpdatePerforming listener: @escaping Listener) -> Bool {
     stopListening()
     $mutableState.write { state in
         state.listenerQueue = queue
         state.listener = listener
     }

     var context = SCNetworkReachabilityContext(version: 0,
                                                   info: Unmanaged.passUnretained(self).toOpaque(),
                                                 retain: nil,
                                                release: nil,
                                        copyDescription: nil)
     let callback: SCNetworkReachabilityCallBack = { _, flags, info in
         guard let info = info else { return }
         let instance = Unmanaged<NetworkReachabilityManager>.fromOpaque(info).takeUnretainedValue()
            instance.notifyListener(flags)
     }

     let queueAdded = SCNetworkReachabilitySetDispatchQueue(reachability, reachabilityQueue)
     let callbackAdded = SCNetworkReachabilitySetCallback(reachability, callback, &context)

     // Manually call listener to give initial state, since the framework may not.
     if let currentFlags = flags {
        reachabilityQueue.async {
            self.notifyListener(currentFlags)
        }
     }

     return callbackAdded && queueAdded
}

/// Stops listening for changes in network reachability status.
open func stopListening() {
    SCNetworkReachabilitySetCallback(reachability, nil, nil)
    SCNetworkReachabilitySetDispatchQueue(reachability, nil)
    $mutableState.write { state in
        state.listener = nil
        state.listenerQueue = nil
        state.previousStatus = nil
    }
}

You can also use Apple's SCNetworkReachbility class instead.

Noor
  • 967
  • 7
  • 18