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 3.0: Here's very simple way to do it:
and then simply you can use it anywhere in your project for example:
This code would be helpful for you. it worked for me in Swift 4 and Xcode 9
Go to https://github.com/ashleymills/Reachability.swift/tree/master/Reachability and copy Reachability.swift file to your project
Vasil Nunev clearly explain this Reachability https://www.youtube.com/watch?v=wDZmz9IsB-8
Another solution for Swift 4.0. Not a big fan o IUO rather use a guard
Swift 4/Xcode 9+ (make Reachability.swift file):
usage:
Create a Swift file within your project, name it: Reachability.swift". then paste below code in this Reachability.swift file:-
Then you can check the internet anywhere in the project using below code
You can use in swift 3