Apple 的 例程 Reachability 中介绍了取得/检测网络状态的方法。在你的程序中使用 Reachability 只须将该例程中的 Reachability.h 和 Reachability.m 拷贝到你的工程中。
Reachability 中定义了3种网络状态:
NotReachable
无连接
ReachableViaCarrierDataNetwork (ReachableViaWWAN)
使用3G/GPRS网络
ReachableViaWiFiNetwork (ReachableViaWiFi)
使用WiFi网络
检测莫个特定站点的连接状况
Reachability *r = [Reachability reachabilityWithHostName:@"www.apple.com"];
switch ([r currentReachabilityStatus])
{
case NotReachable:
// 没有网络连接
break;
case ReachableViaWWAN:
// 使用3G网络
break;
case ReachableViaWiFi:
// 使用WiFi网络
break;
}
检测当前网络环境
// 是否wifi
+ (BOOL) IsEnableWIFI
{
return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
}
// 是否3G
+ (BOOL) IsEnable3G
{
return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);
}
连接状态实时通知
#import "AppDelegate.h"
#import "Reachability.h"
@interface AppDelegate ()
{
Reachability *hostReach;
}
@end
@implementation AppDelegate
- (void)reachabilityChanged:(NSNotification *)note {
Reachability *curReach = [note object];
NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
NetworkStatus state = [curReach currentReachabilityStatus];
if (state == NotReachable) {
[self alertWithMessage:@"没有网络"];
}else if (state == ReachableViaWiFi){
[self alertWithMessage:@"wifi网络"];
}else if (state == ReachableViaWWAN){
[self alertWithMessage:@"移动网络"];
}
}
- (void)alertWithMessage:(NSString *)message{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络状态" message:message delegate:nil cancelButtonTitle:@"YES" otherButtonTitles:nil, nil];
[alert show];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 检测网络状态
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
[hostReach startNotifier];
return YES;
}
我写的一个例子,给大家参考,希望对大家有所帮助
https://github.com/qcx123/NetworkMonitoring.git