Detecting if the wifi is enabled in swift

主宰稳场 提交于 2019-12-21 20:38:19

问题


In my app i have some NSURLConnection.sendAsynchronousRequest but because of that if the user has wifi disabled the app crashes.

Is there a way to detect if the wifi is disabled so i can do something like that:

if(wifi is enabled)
{
    NSURLConnection.sendAsynchronousRequest
}

回答1:


Found the answer in this blog post:

Step 1:

Add "SystemConfiguration" framework 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)
}



回答2:


And now for a 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)
}


来源:https://stackoverflow.com/questions/26086488/detecting-if-the-wifi-is-enabled-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!