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?