For iOS 9 I was using Reachability public class to check wether the device is connected to the internet or not. I converted my Swift 2 code to Swift 3, and the Reachability doesn't work anymore. Can someone tell me how to check the internet connection on iOS 10? Thanks! Here's the code snippet:
open class Reachability {
class func isConnectedToNetwork() -> 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) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}
var flags = SCNetworkReachabilityFlags()
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
return false
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
}
}
Swift 4 / Xcode 10:
I would combine two functions ( with a bit changes) are taken from the solutions by @Pavle Mijatovic and @Krutagn Patel (with thanks) to answer @Lance Samaria question. :)
I almost checked all the possibilities. (the code can be enhanced, but it works fine)
have a class as below:
use the below code where you need to check the Internet connection: for example, in appDelegate -> applicationDidBecomeActive function.
explanation: whenever completionHandler function (above) is called, the result (true or false) is passed to the below code as
b
. so if b is true you have the Internet connection.Try this, it works for me first import the SystemConfiguration to your class.
And now implement bellow function.
step 1 : create a swift file in your project. i created "ConnectionCheck.swift"
step 2 : add this code in your "ConnectionCheck.swift" file and "import SystemConfiguration" file to your "ConnectionCheck.swift" and "ViewController.swift"
}
step 3 : Now in "ViewController.swift" use this code to check Network Reachability
This works in iOS 10
Here is Swift 3 solution via callback function,
isConnectedToNetwork()
is taken from the solution by Yasin Ugurlu from above.1) Create a new Swift file within your project, name it “Reachability.swift”.
2) Cut & paste the following code into it to create your class.
3) You can check internet connection anywhere in your project using this code:
4)If the user is not connected to the internet, you may want to show them an alert dialog to notify them.