0

How can you notify the user that there is no network connection with swift 3. I have tried a bunch of solutions and none of them have worked so far. I am not looking for the speed of the network connection

shallowThought
  • 19,212
  • 9
  • 65
  • 112
GoGode
  • 85
  • 1
  • 10
  • 1
    Possible duplicate of [How to check the network speed using swift](https://stackoverflow.com/questions/38635804/how-to-check-the-network-speed-using-swift) – Rob Jun 29 '17 at 11:39
  • 1
    Possible duplicate of [popup alert when Reachability connection is lost during using the app (IOS xcode swift)](https://stackoverflow.com/questions/31400192/popup-alert-when-reachability-connection-is-lost-during-using-the-app-ios-xcode) – fpg1503 Jun 29 '17 at 12:26

1 Answers1

5

There are a lot of resources showing how to check the Internet connection. E.g., from this.

    func isInternetAvailable() -> Bool
    {
        var zeroAddress = sockaddr_in()
        zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
        zeroAddress.sin_family = sa_family_t(AF_INET)

        let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
            $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
                SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
            }
        }

        var flags = SCNetworkReachabilityFlags()
        if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
            return false
        }
        let isReachable = flags.contains(.reachable)
        let needsConnection = flags.contains(.connectionRequired)
        return (isReachable && !needsConnection)
    }

    func showAlert() {
        if !isInternetAvailable() {
            let alert = UIAlertController(title: "Warning", message: "The Internet is not available", preferredStyle: .alert)
            let action = UIAlertAction(title: "Dismiss", style: .default, handler: nil)
            alert.addAction(action)
            present(alert, animated: true, completion: nil)
        }
    }

You need to import:

import Foundation
import SystemConfiguration
Lawliet
  • 3,438
  • 2
  • 17
  • 28