Detect if Wi-Fi is turned on in fast

In my application, I have NSURLConnection.sendAsynchronousRequest, but because of this, if the user has disabled Wi-Fi, the application is disconnected.

Is there a way to determine if Wi-Fi is disabled, so I can do something like this:

if(wifi is enabled)
{
    NSURLConnection.sendAsynchronousRequest
}
+3
source share
2 answers

Found the answer in this blog post :

Step 1:

Add "SystemConfiguration" to your project

Step 2:

Add this function to your project:

func isConnectionAvailble()->Bool{

    var rechability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "www.apple.com").takeRetainedValue()

    var flags : SCNetworkReachabilityFlags = 0

    if SCNetworkReachabilityGetFlags(rechability, &flags) == 0
    {
        return false
    }

    let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
    return (isReachable && !needsConnection)
}
+3
source

And now for Swift 2.0:

func isConnectionAvailble()->Bool{

    let rechability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "www.apple.com")

    var flags : SCNetworkReachabilityFlags = SCNetworkReachabilityFlags()

    if SCNetworkReachabilityGetFlags(rechability!, &flags) == false {
        return false
    }

    let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0

    return (isReachable && !needsConnection)
}
+4
source

Source: https://habr.com/ru/post/1629222/


All Articles