2

可能重复:
Apples Reachability 类是否有更复杂的替代方案?

这是一个例子:

Reachability *reachability = [Reachability reachabilityForInternetConnection];    
NetworkStatus internetStatus = [reachability currentReachabilityStatus];
if (internetStatus != NotReachable) {
    // Internet is reachable. Start download in background.
} else {
    // Create UIAlertView and tell user there is no functional internet!
}

问题:我听说在某些情况下 WiFi“可能需要连接 VPN on Demand ”。那么我应该如何正确地通知用户有关非功能性互联网连接的信息?我认为上面的代码不足以解决这个问题。

4

1 回答 1

6

Here is what I usually do, I didn't try it on VPN though! I create a standalone class for the checking the connection, say it is named WifiCheckClass.

In the .h file of the class:

#import <Foundation/Foundation.h>
#import "SystemConfiguration/SCNetworkReachability.h"

@interface UIDevice (DeviceConnectivity)
+(BOOL) cellularConnected;
+(BOOL) wiFiConnected;
+(BOOL) networkConnected;
@end

In the .m file:

#import "WiFiCheckClass.h"

@implementation UIDevice (DeviceConnectivity)

+(BOOL) cellularConnected
{
    SCNetworkReachabilityFlags  flags = 0;
    SCNetworkReachabilityRef netReachability;
    netReachability = SCNetworkReachabilityCreateWithName(CFAllocatorGetDefault(), [@"www.google.com" UTF8String]);
    if(netReachability)
    {
        SCNetworkReachabilityGetFlags(netReachability, &flags);
        CFRelease(netReachability);
    }
    if(flags & kSCNetworkReachabilityFlagsIsWWAN) return YES;
    return NO;
}

+(BOOL) networkConnected
{
    SCNetworkReachabilityFlags flags = 0;
    SCNetworkReachabilityRef netReachability;
    BOOL  retrievedFlags = NO;
    netReachability = SCNetworkReachabilityCreateWithName(CFAllocatorGetDefault(), [@"www.google.com" UTF8String]);
    if(netReachability)
    {
        retrievedFlags  = SCNetworkReachabilityGetFlags(netReachability, &flags);
        CFRelease(netReachability);
    }
    if (!retrievedFlags || !flags) return NO;
    return YES;
}

+(BOOL) wiFiConnected
{
    if ([self cellularConnected]) return NO;
    return [self networkConnected];
}

@end

Now using it is very straight forward:

if( [UIDevice wiFiConnected] || [UIDevice networkConnected] || [UIDevice cellularConnected] )
{
    //do what you want
}
于 2012-05-29T16:46:08.793 回答