首页 > 代码库 > iOS 判断当前网络状态
iOS 判断当前网络状态
1.如果只判断当前是否是无网的状态:
if([Reachability reachabilityForLocalWiFi].currentReachabilityStatus==NotReachable&&[[Reachability reachabilityForInternetConnection] currentReachabilityStatus]==NotReachable)
{
//没网的操作
}else
{
//有网的操作
}
2.监听网络状态的改变
导入头文件
#import "Reachability.h"
//注册通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange:) name:kReachabilityChangedNotification object:nil];
self.conn = [Reachability reachabilityForInternetConnection];
[self.conn startNotifier];
(以上代码的conn是Reachability对象)
- (void)networkStateChange:(NSNotification *)note
{
// 通过通知对象获取被监听的Reachability对象
Reachability *curReach = [note object];
// 获取Reachability对象的网络状态
NetworkStatus status = [curReach currentReachabilityStatus];
if (status == ReachableViaWWAN)
{
NSLog(@"3G在线");
}else if (status == ReachableViaWiFi)
{
NSLog(@"WIFI在线");
}else if (status == NotReachable)
{
NSLog(@"没网");
}
}
iOS 判断当前网络状态