一般有兩種方式,都是第三方的架構,輪子嘛,能用就先用著,後面再最佳化。
一:Reachability
1.首先在AppDelegate.h添加標頭檔"Reachability.h",匯入架構SystemConfiguration.frame。
2. 在AppDelegate.m中這樣實現:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{//開啟網路狀況的監聽//來訂閱即時的網路狀態變化通知。匯入Reachability.h標頭檔,然後註冊一個對象來訂閱網路狀態變化的資訊,網路狀態變化的資訊名稱為kReachabilityChanged-Notification[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];//通過檢查某個主機能否訪問來判斷當前網路是否可用:self.hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"] ;//開始監聽,會啟動一個run loop[self.hostReach startNotifier];}-(void)reachabilityChanged:(NSNotification *)note{Reachability *currReach = [note object];NSParameterAssert([currReach isKindOfClass:[Reachability class]]);//對串連改變做出響應處理動作NetworkStatus status = [currReach currentReachabilityStatus];//如果沒有串連到網路就彈出提醒實況self.isReachable = YES;if(status == NotReachable){UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"網路連接異常" message:nil delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];[alert show];[alert release];self.isReachable = NO;return;}if (status==kReachableViaWiFi||status==kReachableViaWWAN) {UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"網路連接資訊" message:@"網路連接正常" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];// [alert show];[alert release];self.isReachable = YES;}}
然後在每個頁面的viewWillAppear:加上:
-(void)viewWillAppear:(BOOL)animated{[super viewWillAppear:YES];AppDelegate *appDlg = (AppDelegate *)[[UIApplication sharedApplication] delegate];if(appDlg.isReachable){NSLog(@"網路已串連");//執行網路正常時的代碼}else{NSLog(@"網路連接異常");//執行網路異常時的代碼UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"網路連接異常" message:nil delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];[alert show];[alert release];}}
這樣就可以檢查到在運行程式時網路突然的中斷和串連。Reachability類實際上是蘋果公司對SCNetworkReachability API的封裝,這個API定義在SystemConfigure.framework庫中。如果有其他特別的需求,也可以直接使用這個原生的SCNetworkReachability類。
二:AFNetworking監測
1.匯入架構,和標頭檔#import <AFNetworkReachabilityManager.h>
2.代碼:
-(void)afn{//1.建立網路狀態監測管理者AFNetworkReachabilityManager *manger = [AFNetworkReachabilityManager sharedManager];//開啟監聽,記得開啟,不然不走block[manger startMonitoring];//2.監聽改變[manger setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {/*AFNetworkReachabilityStatusUnknown = -1,AFNetworkReachabilityStatusNotReachable = 0,AFNetworkReachabilityStatusReachableViaWWAN = 1,AFNetworkReachabilityStatusReachableViaWiFi = 2,*/switch (status) {case AFNetworkReachabilityStatusUnknown:NSLog(@"未知");break;case AFNetworkReachabilityStatusNotReachable:NSLog(@"沒有網路");break;case AFNetworkReachabilityStatusReachableViaWWAN:NSLog(@"3G|4G");break;case AFNetworkReachabilityStatusReachableViaWiFi:NSLog(@"WiFi");break;default:break;}}];}
以上所述是小編給大家介紹的iOS 檢測網路狀態的兩種方法,希望對大家有所協助,如果大家有任何疑問請給我留言,小編會及時回複大家的。在此也非常感謝大家對雲棲社區網站的支援!