问题
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