Search code examples
swiftxcodenetwork-programmingconnectionmonitor

Checking Internet Connection in SWIFT


what’s the easiest way to check internet connection?

I found this code example but is the most efficient way in Xcode11/Swift5?

I only need to check for connection under a button press before calling my function which downloads from the internet. So a simple check before calling my function will do it. Is this constant monitoring the most efficient? Or should I use something directly under my button press.

import Network

class ViewController: UIViewController {

let monitor = NWPathMonitor()
let queue = DispatchQueue(label: "InternetConnectionMonitor")

override func viewDidLoad() {
    monitor.pathUpdateHandler = { pathUpdateHandler in
        if pathUpdateHandler.status == .satisfied {
            print("Internet connection is on.")
        } else {
            print("There's no internet connection.")
        }
    }

    monitor.start(queue: queue)
}

}

Solution

  • I used for this the Reachability framework by ashleymills: https://github.com/ashleymills/Reachability.swift

    You just need to import via: import ReachabilitySwift

    Then just inside your view controller you can do e.g.:

    let reachability = try! Reachability()
    
    if reachability.isReachable {
       print("Internet connection is on.")
    }
    

    See the ReadMe of the repo for more examples on how to use the closures. Beware that it is an external framework and might not be up to date with the latest Swift version.