Check if iPhone is connected to the internet [duplicate]
Asked Answered
J

3

2

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

Thanks...

Juggle answered 25/5, 2011 at 18:40 Comment(0)
L
5

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

Loidaloin answered 25/5, 2011 at 18:41 Comment(1)
That way is more simple:Juggle
D
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.

Declared answered 25/5, 2011 at 19:23 Comment(1)
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.Sail
B
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!!

Begrudge answered 31/10, 2015 at 3:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.