检测是否在swift中启用了wifi

时间:2014-09-28 15:31:08

标签: asynchronous swift wifi

在我的应用程序中,我有一些NSURLConnection.sendAsynchronousRequest但是因为如果用户禁用了wifi,应用程序崩溃了。

有没有办法检测wifi是否被禁用,所以我可以这样做:

if(wifi is enabled)
{
    NSURLConnection.sendAsynchronousRequest
}

2 个答案:

答案 0 :(得分:4)

现在是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)
}

答案 1 :(得分:3)

Found the answer in this blog post

第1步:

添加" SystemConfiguration"项目的框架

第2步:

将此功能添加到您的项目中:

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)
}