When I try to check for an internet connection on my iPhone I get a bunch of errors. Can anyone help me to fix this?
The code:
import Foundation
import SystemConfiguration
public class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}
var flags: SCNetworkReachabilityFlags = 0
if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
return false
}
let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection) ? true : false
}
}
The errors with the code:
If it is unreadable, error 1 says:
'Int' is not convertible to 'SCNetworkReachabilityFlags'
Error 2 & 3:
Could not find an overload for 'init' that accepts the supplied arguments
To solve the 4G issue mentioned in the comments I have used @AshleyMills reachability implementation as a reference and rewritten Reachability for Swift 3.1:
updated: Xcode 10.1 • Swift 4 or later
Reachability.swift file
Usage
Initialize it in your AppDelegate.swift didFinishLaunchingWithOptions method and handle any errors that might occur:
And a view controller sample:
Sample Project