Created
June 24, 2020 13:41
-
-
Save Pikachuxxxx/e9cc930e3855c86e6bc86fef2db6effd to your computer and use it in GitHub Desktop.
Swift Internet Connection Manager
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 SystemConfiguration // please import this module in Xcode Project. | |
/** | |
A class to check for internet connectivity in swift | |
*/ | |
public class InternetConnectionManager { | |
//Initialiser Function | |
private init() {} | |
/** | |
A function to check for the internet connection availability in swift | |
- Returns: A boolean indication whether the device is connectied to internet or not. | |
*/ | |
public static func isConnectedToNetwork() -> Bool { | |
var zeroAddress = sockaddr_in() | |
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) | |
zeroAddress.sin_family = sa_family_t(AF_INET) | |
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, { | |
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) { | |
SCNetworkReachabilityCreateWithAddress(nil, $0) | |
} | |
}) else { | |
return false | |
} | |
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment