First, modify your addressReachable method. Instead of
return reachable && (flags & kSCNetworkFlagsReachable);
add the following:
BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);
return (isReachable && !needsConnection) ? YES : NO;
This is the proper way to check for a connection available. Now, if you want to clearly distinguish between cellular and wifi, modify your method to return an int and use the following
BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);
if(isReachable && !needsConnection) // connection is available
{
// determine what type of connection is available
BOOL isCellularConnection = ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0);
NSString *wifiIPAddress = [self getWiFiIPAddress];
if(isCellularConnection)
return 1; // cellular connection available
if(wifiIPAddress)
return 2; // wifi connection available
}
else
return 0; // no connection at all
The getWiFiIPAddress method is courtesy of Matt Brown, and can be found here.
One more thing. The kSCNetworkReachabilityFlagsIsDirect flag can tell you whether the network traffic goes through a gateway or arrives directly. This may be helpful in some cases.
The code works correctly on the device. On the simulator, it will declare that you are connected trough wifi when you are connected through the ethernet cable, and will declare no connection if you are connected through wifi.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…