针对手机平台网络app需要检测当前的网络状态,第三方api的使用介绍。
1.第三方包的下载链接:点击打开链接
2.使用方法:需要使用 通知(NSNotificationCenter),和一些简单的调用。并在需要添加网络监测的地方按步骤添加如下代码:
1) 添加 全局通知
//设置网络中心,添加网络检测
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reachabilityStateChanged:) name:kReachabilityChangedNotification object:nil];
其中 reachabilityStateChanged:是我们自定义的网络改变的调用方法。后面 的kReachalilityChangedNotification 是第三方包的宏定义。
#define kReachabilityChangedNotification @"kNetworkReachabilityChangedNotification"
2)先看看 我们自定义的 reachabilityStateChanged 方法
- (void)reachabilityStateChanged:(NSNotification *)note
{
Reachability *reachability = [note object]; //从网络通知得到相应的Reachability 对象。
NSParameterAssert([reachability isKindOfClass:[Reachability class]]);
//判定当前方法是不是 reachability 类
//定义不同网络的 message方法
NSString *str_3G = @"当前网络为2G或3G";
NSString *str_Wifi = @"当前网络为Wifi";
NSString *str_None = @"当前无网络";
//调用第三方包的 currentReachabilityState 方法 获得当前的 网络类型
switch ([reachability currentReachabilityStatus]) {
case NotReachable:
[self alertView:str_None]; //调用alertView进行通知。
break;
case ReachableViaWiFi:
[self alertView:str_Wifi];
break;
case ReachableViaWWAN:
[self alertView:str_3G];
break;
default:
[self alertView:@"未知错误"];
break;
}
}
- (void)alertView:(NSString *)message
{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"通知" message:message delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
[alertView show];
[alertView release];
}
3)如何开始监听对象呢?
在我们把通知 放进 通知中心之后,我们便要初始化一个 ReachAbility 对象,并赋值相应的 host,进行设置,开始访问。
//设置网络中心,添加网络检测
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reachabilityStateChanged:) name:kReachabilityChangedNotification object:nil];
self.hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
[self.hostReach startNotifier];
//设置检测的对象,开始检测。