How to Check for Internet Connection in iOS using Swift

Last updated on: May 27, 2023

In this tutorial, I’m going to show you an effortless way to monitor the network state (Wifi, Cellular or No connection) in your iOS app using Reachability.swift

Reachability.swift is a replacement for Apple’s Reachability re-written in Swift.

Adding Reachability.swift in your project

Go to https://github.com/ashleymills/Reachability.swift and press Clone or download > Download ZIP:

Unzip it and take the Reachability.swift file (Sources > Reachability.swift) and drag-and-drop it inside your project

On the new window, check the box Copy items if needed and press Finish

Using Reachability.swift

First, declare Reachability:

let reachability = try! Reachability()Code language: Swift (swift)

In the viewWillAppear method, add an observer to the Notification Center, so every time the network state changes, like from Wifi goes to Cellular, this will be detected instantly and call the reachabilityChanged method.

override func viewWillAppear(_ animated: Bool) {
    NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: .reachabilityChanged, object: reachability)
    do {
        try reachability.startNotifier()
    } catch {
        print("Unable to start notifier")
    }
}

@objc func reachabilityChanged(note: Notification) {
    let reachability = note.object as! Reachability

    switch reachability.connection {
    case .wifi:
        print("Wifi Connection")
    case .cellular:
        print("Cellular Connection")
    case .unavailable:
        print("No Connection")
    case .none:
        print("No Connection")
    }
}Code language: Swift (swift)

And in the viewDidDisappear method, remove the stop the notifier and remove the observer.

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    reachability.stopNotifier()
    NotificationCenter.default.removeObserver(self, name: .reachabilityChanged, object: reachability)
}Code language: Swift (swift)
You can find the final project here

If you have any questionsplease feel free to leave a comment below

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments