0

I'm attempting to check for network connectivity in my Swift app, and timeout after a certain number of seconds. I'm running XCode 7 Beta. The code I'm using is from this question's answer, and is here:

class func isConnectedToNetwork() -> 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) == 0 {
            return false
        }

        let isReachable = flags.contains(.Reachable)
        let needsConnection = flags.contains(.ConnectionRequired)
        return (isReachable && !needsConnection)
        }

This code times out after roughly a minute and twenty seconds with no connection (using the network link conditioner in the iOS simulator). I'm unable to find any references online to anyone using this method with a timeout, which seems incredibly strange because one could assume most app timeouts would be specified by the developer rather than whatever the pre-built methods have set.

The other possible way to go about this would be to use NSURLConnection.sendSynchronousRequest() and the timeoutInterval property of NSMutableURLRequest. This uses a hardcoded URL, which is of course less than ideal. How would I go about creating a developer-specified connection timeout using this method?

Community
  • 1
  • 1
Jthami05
  • 101
  • 3
  • 12
  • SCNetworkReachability has also an asynchronous interface, using a callback that is called automatically on changes. Using this (C based) callback is possible with Swift 2. See my latest update to http://stackoverflow.com/a/27142665/1187415. – Martin R Aug 18 '15 at 14:20
  • Is it possible to use SCNetworkReachability's asynchronous model without using a host url? I'm still trying to figure out this process but it looks like host, being used for reachability, is trying to access google.com. What of cases where google.com can't be reached but there is connectivity? – Jthami05 Aug 18 '15 at 19:46

1 Answers1

0

You can add a NSTimer(should be shorter than the timeout) to send connection request to keep alive. The timeout is set by the server instead of the client.

Roger
  • 973
  • 10
  • 15
  • Something along the lines of calling the 'NSTimer.scheduledTimerWithTimeInterval()' with the specified timeout and some method to continue to in case of timeout, then an if branch with isConnectedToNetWork()' as the condition? Doing that sounds like it could work (and I'm trying to debug my attempt at it) but is that what you meant by your answer? – Jthami05 Aug 18 '15 at 17:14
  • @Jthami05 Yes, that's it. – Roger Aug 18 '15 at 17:21