導(dǎo)入頭文件
#import "Reachability.h"
創(chuàng)建屬性
@property(nonatomic,strong)Reachability *reachli; //網(wǎng)絡(luò)檢測
創(chuàng)建網(wǎng)絡(luò)檢測對象
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//創(chuàng)建網(wǎng)絡(luò)檢測對象
self.reachli = [Reachability reachabilityForInternetConnection];
創(chuàng)建通知 并且添加通知
//創(chuàng)建通知 并且添加通知
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(change) name:kReachabilityChangedNotification object:nil];
//開始監(jiān)聽網(wǎng)絡(luò)狀態(tài)
[self.reachli startNotifier];
//調(diào)用change方法
[self change];
}
//接受到通知 網(wǎng)絡(luò)狀態(tài)改變 調(diào)用
-(void)change{
//創(chuàng)建網(wǎng)絡(luò)連接狀態(tài)對象
NetworkStatus status = [self.reachli currentReachabilityStatus];
//判斷網(wǎng)絡(luò)狀態(tài)
switch (status) {
case NotReachable:{
NSLog(@"沒有網(wǎng)絡(luò)");
UIAlertView *aler = [[UIAlertView alloc]initWithTitle:@"網(wǎng)絡(luò)提示" message:@"沒有網(wǎng)絡(luò)鏈接" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
//展示提示框
[aler show];
break;
}
case ReachableViaWiFi:{
NSLog(@"鏈接成功");
UIAlertView *aler = [[UIAlertView alloc]initWithTitle:@"網(wǎng)絡(luò)提示" message:@"鏈接到Wifi" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
//展示提示框
[aler show];
break;
}
case ReachableViaWWAN:{
NSLog(@"鏈接到蜂窩");
UIAlertView *aler = [[UIAlertView alloc]initWithTitle:@"網(wǎng)絡(luò)提示" message:@"鏈接到蜂窩" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
//展示提示框
[aler show];
break;
}
default:
break;
}
}
-(void)dealloc{
//停止網(wǎng)絡(luò)監(jiān)聽
[self.reachli stopNotifier];
//移除通知
[[NSNotificationCenter defaultCenter]removeObserver:self];
}