1.首先添加框架SystemConfiguration.framework。
2.蘋果官方提供了一個叫Reachability的示例程序,便于開發(fā)者檢測網(wǎng)絡(luò)狀態(tài)
https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip?
下載完后,導(dǎo)入項目中
3.在AppDelegate.h定義一個全局變量 ?@property BOOL isConnect; 判斷網(wǎng)絡(luò)狀態(tài)
4.在AppDelegate.m增加通知中心:
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
hostReach = [Reachability reachabilityForInternetConnection];
[self updateInterfaceWithReachability:hostReach];
[hostReach startNotifier];
5.通知中心響應(yīng)的事件,并給isConnect 賦值(PS:每次網(wǎng)絡(luò)改變都會調(diào)用這個函數(shù))
-(void)reachabilityChanged:(NSNotification*)notification
{
// 1.檢測wifi狀態(tài)
Reachability *wifi = [Reachability reachabilityForLocalWiFi];
// 2.檢測手機是否能上網(wǎng)絡(luò)(WIFI\3G\2.5G)
Reachability *conn = [Reachability reachabilityForInternetConnection];
// 3.判斷網(wǎng)絡(luò)狀態(tài)
if ([wifi currentReachabilityStatus] != NotReachable) { // 有wifi
self.isConnect = YES;
NSLog(@"有wifi%d",self.isConnect);
} else if ([conn currentReachabilityStatus] != NotReachable) { // 沒有使用wifi, 使用手機自帶網(wǎng)絡(luò)進行上網(wǎng)
NSLog(@"使用手機自帶網(wǎng)絡(luò)進行上網(wǎng)");
self.isConnect = YES;
} else { // 沒有網(wǎng)絡(luò)
self.isConnect = NO;
NSLog(@"沒有網(wǎng)絡(luò)%d",self.isConnect);
}
}
6.程序啟動是檢測網(wǎng)絡(luò)狀態(tài) ,并給isConnect 賦值
-(void)updateInterfaceWithReachability:(Reachability*)reach
{
//對連接改變做出響應(yīng)的處理動作趟卸。
NetworkStatus status=[reach currentReachabilityStatus];
if (status== NotReachable) { //沒有連接到網(wǎng)絡(luò)就彈出提實況
UIAlertView *alert= [[UIAlertView alloc] initWithTitle:@"提示"
message:@"請檢查網(wǎng)絡(luò)連接狀態(tài)"
delegate:nil
cancelButtonTitle:@"好" otherButtonTitles:nil];
[alert show];
self.isConnect = NO;
NSLog(@"沒網(wǎng)了%d",self.isConnect);
}else {
self.isConnect = YES;
NSLog(@"有網(wǎng)了%d",self.isConnect);
}
}
在想要檢測網(wǎng)絡(luò)狀態(tài)的類里面,實例化AppDelegate對象,調(diào)用isConnect凉夯。
AppDelegate ? *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];