如果用系统的方法需要导入 Reachability.h Reachability.m
@interface ViewController ()
@property (nonatomic, strong) Reachability r1; /*< <#属性名#> */
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
/*
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// nullable : 代表可以为nil
// __nonnull : 代表不能为nil
[manager GET:@"www.520it.com" parameters:nil success:^ void(NSURLSessionDataTask * task, id responseObjc) {
NSLog(@"成功的回调");
} failure:^ void(NSURLSessionDataTask * task, NSError * error) {
NSLog(@"失败的回调");
}];
*/
// 1.创建Reachability对象
self.r1 = [Reachability reachabilityForLocalWiFi];
// 2.给Reachability对象注册通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNetworkStatus) name:kReachabilityChangedNotification object:nil];
// 3.让Reachability对象发送网络改变的通知
[self.r1 startNotifier];
}
(void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}(void)getNetworkStatus
{
if ([Reachability reachabilityForLocalWiFi].currentReachabilityStatus != NotReachable) {
NSLog(@"当前是蜂窝网");
}else if ([Reachability reachabilityForInternetConnection].currentReachabilityStatus != NotReachable)
{
NSLog(@"当前是蜂窝网");
}else
{
NSLog(@"没有网络");
}
}(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent )event
{
/
// 1.创建Reachability对象
// 创建一个蜂窝网的Reachability对象
Reachability *r1 = [Reachability reachabilityForInternetConnection];
// 2.获取当前对象的网络状态, 如果不是NotReachable值, 那么就代表当前的网络状态是我们创建的类型
if(r1.currentReachabilityStatus != NotReachable)
{
NSLog(@"当前是蜂窝网");
}
// 创建一个局域网的Reachability对象
Reachability *r2 = [Reachability reachabilityForLocalWiFi];
if(r2.currentReachabilityStatus != NotReachable)
{
NSLog(@"当前是蜂窝网");
}
*/
}
-
(void)afnReachability
{
// 1.创建网络监听管理者
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];// 2.设置网络变化的回调
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
// 只要用户的网络发生改变, 就会调用这个block
/*
AFNetworkReachabilityStatusUnknown = 不能识别,
AFNetworkReachabilityStatusNotReachable = 没有网络,
AFNetworkReachabilityStatusReachableViaWWAN = 蜂窝网,
AFNetworkReachabilityStatusReachableViaWiFi = 局域网,
*/
switch (status) {
case AFNetworkReachabilityStatusReachableViaWWAN:
NSLog(@"蜂窝网");
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
NSLog(@"局域网");
break;
case AFNetworkReachabilityStatusNotReachable:
NSLog(@"没有网络");
break;
default:
NSLog(@"不能识别");
break;
}
}];// 3.开始监听
[manager startMonitoring];
}
@end