开发Web等网络应用程序的时候,需要确认网络环境,连接情况等信息。如果没有处理它们,是不会通过Apple的审查的。Apple的例程Reachability中介绍了取得/检测网络状态的方法。要在应用程序中使用Reachability需要添加源文件(只需添加Reachability.h和Reachability.m文件)和framework(将SystemConfiguration.framework)。
在Reachability.h中定义了三种网络状态:
typedef enum{
NotReachable = 0, // 无网络连接
ReachableViaWiFi, // 使用WiFi网络
ReachableViaWWAN // 使用3G/GPRS网络
}NetworkStatus;
1.
Reachability *reach = [Reachability reachabilityWithHostName:@”www.apple.com”];
Switch([reach currentReachabilityStatus]) {
case NotReachale:
// 没有网络连接
break;
case ReachableViaWWAN:
// 使用3G网络
break;
case ReachableViaWiFi:
// 使用WiFi网络
break;
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dd:) name:kReachabilityChangedNotification object:nil];
[reach startNotifier];
-(void)dd:(NSNotification *)notification
{
Reachability *reach = [notification object];
if (![reach isReachable]) {
// 这里创建一个提示框(UIAlertView即可)
}
}
2. 检查当前网络环境
程序启动时,如果想检测可用的网络环境,可以像这样
+(BOOL)IsEnableWIFI {
return([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
} // 是否是WiFi
+(BOOL)IsEnable3G {
return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);
} // 是否3G