Frage

Possible Duplicate:
Are there more sophisticated alternatives to Apples Reachability class?

Here's an example:

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

Problem: I've heard that in some cases WiFi "may require a connection for VPN on Demand". So how am I supposed to correctly notify the user about a non-functional internet connection? I assume that the code above is not enough to deal with this.

War es hilfreich?

Lösung

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
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top