Reachability.swift 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. //
  2. // Reachability.swift
  3. // LMS
  4. //
  5. // Created by Suraj Kumar Mandal on 26/08/22.
  6. //
  7. import Foundation
  8. import SystemConfiguration
  9. public class Reachability {
  10. class func isConnectedToNetwork() -> Bool {
  11. var zeroAddress = sockaddr_in()
  12. zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
  13. zeroAddress.sin_family = sa_family_t(AF_INET)
  14. guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
  15. $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
  16. SCNetworkReachabilityCreateWithAddress(nil, $0)
  17. }
  18. }) else {
  19. return false
  20. }
  21. var flags: SCNetworkReachabilityFlags = []
  22. if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
  23. return false
  24. }
  25. let isReachable = flags.contains(.reachable)
  26. let needsConnection = flags.contains(.connectionRequired)
  27. return (isReachable && !needsConnection)
  28. }
  29. }