iOS中使用 Reachability 检测网络

Apple 的 例程 Reachability 中介绍了取得/检测网络状态的方法。在你的程序中使用 Reachability 只须将该例程中的 Reachability.h 和 Reachability.m 拷贝到你的工程中。如下图

然后将 SystemConfiguration.framework 添加进工程:

Reachability 中定义了3种网络状态。

typedefenum{
NotReachable= 0,
ReachableViaWiFi,
ReachableViaWWAN
} NetworkStatus;



  1. #import <UIKit/UIKit.h>  
  2. #import "Reachability.h"  
  3.   
  4. @interface AppDelegate : UIResponder <UIApplicationDelegate>  
  5.   
  6. @property (strongnonatomicUIWindow *window;  
  7. @property (strongnonatomicReachability *reach;  
  8.   
  9. @end  


  1. #import "AppDelegate.h"  
  2. #import "MainViewController.h"  
  3.   
  4. @implementation AppDelegate  
  5.   
  6. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
  7. {  
  8.     self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];  
  9.     // Override point for customization after application launch.  
  10.     self.window.backgroundColor = [UIColor whiteColor];  
  11.       
  12.     self.window.rootViewController = [[MainViewController alloc]init];  
  13.       
  14.     ///开启网络状况的监听  
  15.     [[NSNotificationCenter defaultCenter] addObserver:self  
  16.                                              selector:@selector(reachabilityChanged:)  
  17.                                                  name:kReachabilityChangedNotification  
  18.                                                object:nil];  
  19.       
  20.     self.reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];  
  21.       
  22.     [self.reach startNotifier]; //开始监听,会启动一个run loop  
  23.       
  24.       
  25.     [self.window makeKeyAndVisible];  
  26.     return YES;  
  27. }  
  28.   
  29. //通知  
  30. -(void)reachabilityChanged:(NSNotification*)note  
  31. {  
  32.     Reachability * reach = [note object];  
  33.     NSParameterAssert([reach isKindOfClass: [Reachability class]]);  
  34.     NetworkStatus status = [reach currentReachabilityStatus];  
  35.       
  36. //    //用于检测是否是WIFI  
  37. //    NSLog(@"%d",([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable));  
  38. //    //用于检查是否是3G  
  39. //    NSLog(@"%d",([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable));  
  40.       
  41.     if (status == NotReachable) {  
  42.         UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"网络已断开" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];  
  43.         [alertView show];  
  44.         NSLog(@"Notification Says Unreachable");  
  45.     }else if(status == ReachableViaWWAN){  
  46.           
  47.           
  48.         UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"移动网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];  
  49.         [alertView show];  
  50.         NSLog(@"Notification Says mobilenet");  
  51.     }else if(status == ReachableViaWiFi){  
  52.           
  53.         UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"WIfi网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];  
  54.         [alertView show];  
  55.         NSLog(@"Notification Says wifinet");  
  56.     }  
  57.       
  58. }  
  59.   
  60. - (void)dealloc {  
  61.     // 删除通知对象  
  62.     [[NSNotificationCenter defaultCenter] removeObserver:self];  
  63.   
  64. }  
  65.   
  66.   
  67. - (void)applicationWillResignActive:(UIApplication *)application  
  68. {  
  69.     // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.  
  70.     // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.  
  71. }  
  72.   
  73. - (void)applicationDidEnterBackground:(UIApplication *)application  
  74. {  
  75.     // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.   
  76.     // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.  
  77. }  
  78.   
  79. - (void)applicationWillEnterForeground:(UIApplication *)application  
  80. {  
  81.     // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.  
  82. }  
  83.   
  84. - (void)applicationDidBecomeActive:(UIApplication *)application  
  85. {  
  86.     // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.  
  87. }  
  88.   
  89. - (void)applicationWillTerminate:(UIApplication *)application  
  90. {  
  91.     // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.  
  92. }  



在要用的地方:

  1. - (void)viewDidLoad  
  2. {  
  3.     [super viewDidLoad];  
  4.     UIButton *btn = [UIButton buttonWithType:UIButtonTypeContactAdd];  
  5.     btn.center = CGPointMake(100200);  
  6.     [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];  
  7.     [self.view addSubview:btn];  
  8.   
  9. }  
  10.   
  11. -(void)btnClick  
  12. {  
  13.     AppDelegate *appDlg = (AppDelegate *)[[UIApplication sharedApplication] delegate];  
  14.     NSParameterAssert([appDlg.reach isKindOfClass: [Reachability class]]);  
  15.     NetworkStatus status = [appDlg.reach currentReachabilityStatus];  
  16.       
  17.     if (status == NotReachable) {  
  18. //        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"网络已断开" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];  
  19. //        [alertView show];  
  20.         NSLog(@"----Notification Says Unreachable");  
  21.     }else if(status == ReachableViaWWAN){  
  22. //        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"移动网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];  
  23. //        [alertView show];  
  24.         NSLog(@"----Notification Says mobilenet");  
  25.     }else if(status == ReachableViaWiFi){  
  26. //        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"WIfi网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];  
  27. //        [alertView show];  
  28.         NSLog(@"----Notification Says wifinet");  
  29.     }  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值