轉載網址: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
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
- {
- self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
-
- //開啓網絡情況的監聽
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
-
- self.hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"] ;
- [self.hostReach startNotifier]; //開始監聽,會啓動一個run loop
-
- self.window.rootViewController = self.tabBarController;
- [self.window makeKeyAndVisible];
- return YES;
- }
-
- //網絡連接改變時會調用的方法
- -(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:@"暫沒法訪問書城信息" delegate:nil cancelButtonTitle:@"肯定" otherButtonTitles:nil];
- [alert show];
- [alert release];
- self.isReachable = NO;
- }
- else
- {
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"網絡鏈接信息" message:@"網絡鏈接正常" delegate:nil cancelButtonTitle:@"肯定" otherButtonTitles:nil];
- [alert show];
- [alert release];
- self.isReachable = YES;
- }
- }
經過如上代碼,在應用程序的任何一個界面均可以使用下面的單例來判斷網絡是否鏈接
- AppDelegate *appDlg = (AppDelegate *)[[UIApplication sharedApplication] delegate];
- if(appDlg.isReachable)
- {
- NSLog(@"網絡已鏈接");//執行網絡正常時的代碼
- }
- else
- {
- NSLog(@"網絡鏈接異常");//執行網絡異常時的代碼
- }
而後就能夠執行響應的操做了,這樣使用監聽的好處就是,沒必要在每個須要檢測網絡連接狀況的地方都寫一大堆代碼,只須要上面的監聽,網絡改變的時候,在任何一個地方均可以自定提醒用戶。