自動檢測iOS網絡並可跳轉至設置界面設置網絡

轉載網址:http://blog.sina.com.cn/s/blog_6bb90d70010123h8.html html

尚未對這篇文章中提到的 嘗試過,誰用過以後 能夠達到效果,吱一聲哈! 網絡

若不想寫繁瑣的網絡情況判斷代碼,而且應用程序能自動在無網絡時彈出可跳轉到系統設置頁面的對話框,那麼能夠考慮這麼作。
在項目中相應的**info.plist文件中增長一個關鍵字:
<key>SBUsesNetwork</key>
<true/>

應用程序就會自動檢測網絡情況,在網絡異常的狀況下,會彈出網絡設置對話框提醒用戶是否進行網絡設置,而且能夠跳轉至系統設置中進行昂立設置。 app


其實在IOS5.1+以後,蘋果就刪除了程序跳轉至設置界面的功能了,不知道爲何。。。 oop

因此本身寫代碼也是不可能實現的,只可以對網絡進行監聽,而後提醒用戶網絡連接異常而已。 spa

下面是監聽網絡改變的代碼,能夠參考一下: .net

在AppDelegate.m中寫以下代碼: server

[cpp]  view plain copy
  1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
  2. {  
  3.     self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];  
  4.       
  5.     //開啓網絡情況的監聽  
  6.     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];  
  7.       
  8.     self.hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"] ;  
  9.     [self.hostReach startNotifier];  //開始監聽,會啓動一個run loop  
  10.   
  11.     self.window.rootViewController = self.tabBarController;  
  12.     [self.window makeKeyAndVisible];  
  13.     return YES;  
  14. }  
  15.   
  16. //網絡連接改變時會調用的方法  
  17. -(void)reachabilityChanged:(NSNotification *)note  
  18. {  
  19.     Reachability *currReach = [note object];  
  20.     NSParameterAssert([currReach isKindOfClass:[Reachability class]]);  
  21.       
  22.     //對鏈接改變作出響應處理動做  
  23.     NetworkStatus status = [currReach currentReachabilityStatus];  
  24.     //若是沒有鏈接到網絡就彈出提醒實況  
  25.     self.isReachable = YES;  
  26.     if(status == NotReachable)  
  27.     {  
  28.         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"網絡鏈接異常" message:@"暫沒法訪問書城信息" delegate:nil cancelButtonTitle:@"肯定" otherButtonTitles:nil];  
  29.         [alert show];  
  30.         [alert release];  
  31.         self.isReachable = NO;  
  32.     }  
  33.     else  
  34.     {  
  35.         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"網絡鏈接信息" message:@"網絡鏈接正常" delegate:nil cancelButtonTitle:@"肯定" otherButtonTitles:nil];  
  36.         [alert show];  
  37.         [alert release];  
  38.         self.isReachable = YES;  
  39.     }  
  40. }  

經過如上代碼,在應用程序的任何一個界面均可以使用下面的單例來判斷網絡是否鏈接

[cpp]  view plain copy
  1. AppDelegate *appDlg = (AppDelegate *)[[UIApplication sharedApplication] delegate];  
  2. if(appDlg.isReachable)  
  3. {  
  4.     NSLog(@"網絡已鏈接");//執行網絡正常時的代碼  
  5. }  
  6. else  
  7. {  
  8.     NSLog(@"網絡鏈接異常");//執行網絡異常時的代碼  
  9. }  
而後就能夠執行響應的操做了,這樣使用監聽的好處就是,沒必要在每個須要檢測網絡連接狀況的地方都寫一大堆代碼,只須要上面的監聽,網絡改變的時候,在任何一個地方均可以自定提醒用戶。
相關文章
相關標籤/搜索