標籤:
#import "ViewController.h"
#import "Reachability.h"
//註:工程需要引入Reachability.h 與 Reachability.m
@interface ViewController ()
@property(nonatomic,strong)Reachability *reach;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 判斷能否串連到某一個主機
// http://www.baidu.com
self.reach = [Reachability reachabilityWithHostName:@"baidu.com"];
// 添加通知 監測網路狀態
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged) name:kReachabilityChangedNotification object:nil];
// 開始監聽
[self.reach startNotifier];
}
- (void)dealloc
{
// 停止監聽
[self.reach stopNotifier];
// 移除監聽 // 移除整個控制器裡所有的監聽
// [[NSNotificationCenter defaultCenter] removeObserver:self];
// 移除控制器裡的kReachabilityChangedNotification監聽
[[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];
}
- (void)reachabilityChanged
{
// 網路狀態
switch (self.reach.currentReachabilityStatus) {
case NotReachable:
NSLog(@"沒有串連");
break;
case ReachableViaWiFi:
NSLog(@"WiFi");
break;
case ReachableViaWWAN:
NSLog(@"WWAN");
break;
default:
NSLog(@"無");
break;
}
}
@end
iOS 連網狀態監測