SCNetworkReachabilityCreateWithAddress is being deprecated

62 views Asked by At

Apple has deprecated SCNetworkReachabilityCreateWithAddress and while the documentation does not state that SCNetworkReachabilityGetFlags is also deprecated it looks like both are on the way out. Apple does not suggest a successor so my question is what would be a good way to achieve a similar result to test reachability? Here is the code I was using:

var currentReachabilityStatus: ReachabilityStatus {
    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
    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 .notReachable
    }
    
    var flags: SCNetworkReachabilityFlags = []
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
        return .notReachable
    }
...

My current code works but the feature is being retired.

1

There are 1 answers

0
J W On BEST ANSWER

It is recommended to use Network's NWPathMonitor Method explanation

Example:

import Network

class Reachability {
  let monitor = NWPathMonitor()
  let queue = DispatchQueue.global(qos: .background)
  
  init() {
    monitor.pathUpdateHandler = { path in
      if path.status == .satisfied {
        // network reachable
      } else {
        // network not reachable
      }
    }
    
    monitor.start(queue: queue)
  }
}