1.通過(guò)AFNetworking的AFNetworkReachabilityManager對(duì)象
監(jiān)聽(tīng)網(wǎng)絡(luò)方法
- (void)netWorkMonitor{
manager = [AFNetworkReachabilityManager sharedManager];
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusUnknown:
[ProgressHUD showSuccess:@"未識(shí)別的網(wǎng)絡(luò)" Interaction:YES];
break;
case AFNetworkReachabilityStatusNotReachable:
[ProgressHUD showSuccess:@"網(wǎng)絡(luò)不可用啡直,請(qǐng)打開(kāi)WiFi或者移動(dòng)蜂窩網(wǎng)絡(luò)" Interaction:YES];
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
[ProgressHUD showError:@"2G,3G,4G...的網(wǎng)絡(luò)" Interaction:YES];
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
[ProgressHUD showSuccess:@"wifi的網(wǎng)絡(luò)" Interaction:YES];
break;
default:
break;
}
}];
[manager startMonitoring];
}
調(diào)用
[self performSelector:@selector(netWorkMonitor) withObject:nil afterDelay:0.2];
2.Reachability對(duì)象
- 必須將 Reachability.h 和 Reachability.m 拷貝到工程中。
- 導(dǎo)入#import "Reachability.h"
//監(jiān)聽(tīng)部分
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
self.reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
// 讓Reachability對(duì)象開(kāi)啟被監(jiān)聽(tīng)狀態(tài)
[self.reach startNotifier];
//網(wǎng)絡(luò)狀態(tài)改變勋乾,彈出alertview提示框涝焙。
- (void)reachabilityChanged:(NSNotification *)note
{
// 通過(guò)通知對(duì)象獲取被監(jiān)聽(tīng)的Reachability對(duì)象
Reachability *curReach = [note object];
// 獲取Reachability對(duì)象的網(wǎng)絡(luò)狀態(tài)
NetworkStatus status = [curReach currentReachabilityStatus];
if (status == NotReachable)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"不能訪問(wèn)網(wǎng)絡(luò)系枪,請(qǐng)檢查網(wǎng)絡(luò)" delegate:nil cancelButtonTitle:@"YES" otherButtonTitles:nil];
[alert show];
}
}
注意:使用Reachability發(fā)通知的時(shí)候单料,在模擬器中網(wǎng)絡(luò)狀態(tài)改變r(jià)eachabilityChanged一直會(huì)被調(diào)用兩次固该,查了好久不知道什么原因扳躬。這種情況不知道只有我碰到了還是脆诉?
- Reachability寫法2
-(void)checkInternet
{
self.internetReachability = [Reachability reachabilityForInternetConnection];
if (self.internetReachability.currentReachabilityStatus==NotReachable)
{
NSLog(@"網(wǎng)絡(luò)不可用...");
[self internetAlertView];
} else{
NSLog(@"網(wǎng)絡(luò)可用...");
}
[self.internetReachability startNotifier];
}
-(void)internetAlertView
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"不能訪問(wèn)網(wǎng)絡(luò),請(qǐng)檢查網(wǎng)絡(luò)!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertView show];
}
3.使用netdb.h
- 必須導(dǎo)入如下頭文件
include<unistd.h>
include<netdb.h>
+ 在Appdelegate.h文件中
-(BOOL)checkInternetConnection;
+ 在Appdelegate.m文件中
-(BOOL)checkInternetConnection {
char *hostname;
struct hostent *hostinfo;
hostname = "baidu.com";
hostinfo = gethostbyname (hostname);
if (hostinfo == NULL)
{
NSLog(@"-> no connection!\n");
return NO;
}
else{
NSLog(@"-> connection established!\n");
return YES;
}
}