0

In my project I have code that I found on this website that checks if the user doesn't have any internet (no wifi or cellular). The code works when a person with no connection opens the tab, but when they open the tab first and then lose connection it fails to detect that. How can I make it so that the function is triggered after the tab is loaded and they lose connection afterwards? Below is the code:

import SystemConfiguration

func connectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)

    guard let defaultRouteReachability = withUnsafePointer(&zeroAddress, {
        SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
    }) else {
        return false
    }

    var flags : SCNetworkReachabilityFlags = []
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
        return false
    }

    let isReachable = flags.contains(.Reachable)
    let needsConnection = flags.contains(.ConnectionRequired)

    // For Swift 3, replace the last two lines by
    // let isReachable = flags.contains(.reachable)
    // let needsConnection = flags.contains(.connectionRequired)


    return (isReachable && !needsConnection)
}
Matt
  • 1,087
  • 1
  • 12
  • 28
  • 1
    There is a brilliant library called Reachability here: https://github.com/ashleymills/Reachability.swift – Shripada Aug 18 '16 at 03:24
  • use `NSTimer` to poll the function at specific interval after the tab loads. – Ayan Sengupta Aug 18 '16 at 03:32
  • @AyanSengupta No, do not poll using a timer. That's a terrible approach. Use `Reachability` and get notified when access changes. – rmaddy Aug 18 '16 at 03:34
  • That code looks familiar: http://stackoverflow.com/a/25623647/1187415. You can register a callback function to get notified about changes: http://stackoverflow.com/a/27142665/1187415. – Martin R Aug 18 '16 at 03:37
  • @rmaddy yes `SCNetworkReachabilitySetCallback` is a far better approach if the user wants continuous updates. I actually misinterpreted the question and thought about a single polling `NSTimer` or may be a `dispatch_after` block. – Ayan Sengupta Aug 18 '16 at 03:43
  • How exactly would I go about using `SCNetworkReachabilitySetCallback`? There are very little helpful code samples online – Matt Aug 18 '16 at 04:26

0 Answers0