2

how I can check quickly if the iPhone is connected to internet or not, quickly...

Thanks...

Nick Weaver
  • 47,228
  • 12
  • 98
  • 108
Maxime
  • 3,167
  • 7
  • 26
  • 33

3 Answers3

5

Have a look at Apple's Reachability class and this example app.

Nick Weaver
  • 47,228
  • 12
  • 98
  • 108
2

You should try to connect to the server with what you think is an appropriate timeout. NEVER use the reachability API until you've determined that your connection attempt failed and even then only if the error you receive from NSURLConnection et. al. is one that suggests you're not connected to the network. In that case, use the Reachability API to determine when you should try again.

Merely attempting a connection may bring up a network interface that wasn't available before.

Mark Pauley
  • 1,445
  • 12
  • 11
  • This answer needs to be emphasized. Reachability has a lot of limitations to it and is not completely reliable. It can return true when there is no connection, in certain situations where network connection fluctuates. The only truly reliable way is to actually handle failure once your actual communication is attempted. Checking beforehand and assuming that it can't change in the meantime is a recipe for unhandled failure. – Leo Flaherty Jun 29 '15 at 09:26
1

You can check for internet connection in swift using code below:

import SystemConfiguration

class Reachability: NSObject {

class func isConnectedToNetwork() -> Bool {
    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)
    let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
        SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
    }
    var flags = SCNetworkReachabilityFlags()
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
        return false
    }
    let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
    return (isReachable && !needsConnection)
}

Hope this helps!!

Manish Verma
  • 539
  • 1
  • 4
  • 11