Last active
February 9, 2024 21:24
-
-
Save ttran4040/74a07380af8c76d1b3d4 to your computer and use it in GitHub Desktop.
Check for Internet Connection (Swift)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import SystemConfiguration | |
public class Reachability { | |
class func isConnectedToNetwork() -> Bool { | |
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) | |
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) | |
zeroAddress.sin_family = sa_family_t(AF_INET) | |
let defaultRouteReachability = withUnsafePointer(&zeroAddress) { | |
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue() | |
} | |
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 | |
} | |
} | |
Example Usage: | |
if Reachability.isConnectedToNetwork() { | |
println("Internet Connection: Available") | |
} else { | |
println("Internet Connection: Unavailable") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment