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
Asked
Active
Viewed 4,175 times
0
-
1Possible 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
-
1Possible 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 Answers
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
-
-
Anywhere, it's up to your design. If you are in a ViewController and want to test then put it there. – Lawliet Jun 29 '17 at 11:59
-
-
1. Call `showAlert()` in `viewDidLoad`? 2. Turn off the Internet? 3. Debug to see if the code is running correctly? – Lawliet Jun 29 '17 at 12:25
-