可能重复:
Are there more sophisticated alternatives to Apples Reachability class?
以下是一个例子:
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 ”。那么我该如何正确地通知用户有关无功能的互联网连接?我假设上面的代码不足以解决这个问题。
答案 0 :(得分:6)
这是我通常做的,虽然我没有在VPN上尝试过!我创建了一个独立的类来检查连接,比如它被命名为WifiCheckClass
。
在班级的.h文件中:
#import <Foundation/Foundation.h>
#import "SystemConfiguration/SCNetworkReachability.h"
@interface UIDevice (DeviceConnectivity)
+(BOOL) cellularConnected;
+(BOOL) wiFiConnected;
+(BOOL) networkConnected;
@end
在.m文件中:
#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
现在使用它非常直接:
if( [UIDevice wiFiConnected] || [UIDevice networkConnected] || [UIDevice cellularConnected] )
{
//do what you want
}