調(diào)用
Reachability.h
頭文件,并創(chuàng)建全局變量Reachability *internetReachability;
在AppDelegate的
- (BOOL)application:(UIApplication )application didFinishLaunchingWithOptions:(NSDictionary )launchOptions
方法中創(chuàng)建通知
//添加一個(gè)系統(tǒng)通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
//初始化
internetReachability=[Reachability reachabilityForInternetConnection];
//通知添加到Run Loop
[internetReachability startNotifier];
[self updateInterfaceWithReachability:internetReachability];
- 實(shí)現(xiàn)通知方法
- (void) reachabilityChanged:(NSNotification *)note
{
Reachability* curReach = [note object];
NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
[self updateInterfaceWithReachability:curReach];
}
- 監(jiān)測網(wǎng)絡(luò)狀態(tài)方法
- (void)updateInterfaceWithReachability:(Reachability *)reachability
{
NetworkStatus netStatus = [reachability currentReachabilityStatus];
switch (netStatus) {
case NotReachable:
NSLog(@"====當(dāng)前網(wǎng)絡(luò)狀態(tài)不可用=======");
break;
case ReachableViaWiFi:
NSLog(@"====當(dāng)前網(wǎng)絡(luò)狀態(tài)為Wifi=======");
break;
case ReachableViaWWAN:
NSLog(@"====當(dāng)前網(wǎng)絡(luò)狀態(tài)為流量=======keso");
break;
}
}
注:
- 此方法能監(jiān)測所有頁面的網(wǎng)絡(luò)狀態(tài),可是要在當(dāng)前頁面獲取當(dāng)前網(wǎng)絡(luò)狀態(tài)則需要使用AFNetWorking,如果不嫌麻煩那就一個(gè)一個(gè)寫.