iOS检测网络状态

有2种方式,可以在AppDelegate直接写:

第一种AFNetworkReachabilityManager:

AFNetworkReachabilityManager *manage = [AFNetworkReachabilityManager >sharedManager];

[manage setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus >status) {
switch (status) {
case AFNetworkReachabilityStatusUnknown: // 未知网络
{
NSLog(@"未知网络");
}
break;
case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
{
NSLog(@"没有网络(断网)");
[MBProgressHUD showError:@"网络异常,请检查网络设置!"];
}
break;
case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
{
NSLog(@"手机自带网络");
}
break;
case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
{
NSLog(@"WIFI");
}
break;
}
}];
// 开始监控
[manage startMonitoring];

 

第二种使用Reachability:

首先github下载Reachability文件
添加源代码

 

代码示例:
导入头文件

import "Reachability.h"

@interface ViewController ( )

@property (nonatomic, strong) Reachability *conn;
@end

@implementation ViewController

(void)viewDidLoad
{
[super viewDidLoad];

[[NSNotificationCenter defaultCenter] addObserver:self >selector:@selector(networkStateChange) >name:kReachabilityChangedNotification object:nil];
self.conn = [Reachability reachabilityForInternetConnection];
[self.conn startNotifier];
}
(void)dealloc
{
[self.conn stopNotifier];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
(void)networkStateChange
{
[self checkNetworkState];
}
(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
}

(void)checkNetworkState
{
// 1.检测wifi状态
Reachability *wifi = [Reachability reachabilityForLocalWiFi];
// 2.检测手机是否能上网络(WIFI\3G\2.5G)

Reachability *conn = [Reachability reachabilityForInternetConnection];
// 3.判断网络状态

if ([wifi currentReachabilityStatus] != NotReachable) { // 有wifi
NSLog(@"有wifi");

} else if ([conn currentReachabilityStatus] != NotReachable) { // 没有使用wifi, 使用手机自带网络进行上网
NSLog(@"使用手机自带网络进行上网");

} else { // 没有网络

NSLog(@"没有网络");
}
}
@end

 

// 用WIFI
// [wifi currentReachabilityStatus] != NotReachable
// [conn currentReachabilityStatus] != NotReachable

// 没有用WIFI, 只用了手机网络

// [wifi currentReachabilityStatus] == NotReachable
// [conn currentReachabilityStatus] != NotReachable

// 没有网络

// [wifi currentReachabilityStatus] == NotReachable
// [conn currentReachabilityStatus] == NotReachable

 

 

posted @ 2021-03-12 08:29  循序渐进A  阅读(279)  评论(0)    收藏  举报