【iOS开发】---- Reachability 网络监测

来源:互联网 发布:mac系统需要升级吗 编辑:程序博客网 时间:2024/05/17 09:32
在开发的过程中,我们需要检测网络状态,比如当前网络状态(连接,断开),网络环境(2G/3G,WIFI)等。苹果提供了一个在iOS环境下检测网络用的库:Reachability。它能方便的监测网络状态,让我们在不同的网络状态下做出对应的处理。

     现在我们来学习Reachability的使用。
     首先我们需要明白以下几个问题:
  • Reachability能做什么
    • 监测网络是否可用
    • 判断当前处于什么网络环境 (2G/3G,WIFI)
    • 监测连接方式的变更
  • 下载
    • 苹果官方:点击下载
    • Git:点击下载(支持arc和GCD)
  • 安装
            方法1.使用Cocoapods直接安装即可。
            方法2.下载Reachability.h和Reachability.m文件,拽入你的工程中,然后添加SystemConfiguration.framework 库即可。
  • 使用
检测网络是否可用。
在 AppDelegate.h文件中添加如下代码
#import <UIKit/UIKit.h>@class Reachability; //ADD@interface AppDelegate : UIResponder <UIApplicationDelegate>@property (nonatomic) Reachability  *hostReach;//ADD@property (strong, nonatomic) UIWindow *window;@end


 AppDelegate.m文件- (BOOL)application:didFinishLaunchingWithOptions:方法中添加如下代码:
      [[NSNotificationCenter defaultCenter] addObserver:self                                             selector:@selector(reachabilityChanged:)                                                 name:kReachabilityChangedNotification                                               object:nil];    self.hostReach = [Reachability reachabilityWithHostName:@"www.apple.com"];    [self.hostReach startNotifier];


reachabilityChanged实现如下:
/* * Called by Reachability whenever status changes. */- (void) reachabilityChanged:(NSNotification *)note{     Reachability* curReach = [note object];     NSParameterAssert([curReach isKindOfClass:[Reachability class]]);     [self updateInterfaceWithReachability:curReach];//更新用户界面,或者在当前状态实现你想要的处理}


Reachability.h中定义了三种网络状态:
typedef enum {   NotReachable = 0,            //无连接   ReachableViaWiFi,           //使用3G/GPRS网络   ReachableViaWWAN       //使用WiFi网络  } NetworkStatus;


在其他控制器中添加相应的通知,即可监测网络,并在其中做出相应的处理。

判断当前的网络环境
如果你想在wifi环境离线数据,那么就需要知道当前处于什么样的网络环境。
  // 是否wifi+ (BOOL) IsEnableWIFI {     return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable); }// 是否3G+ (BOOL) IsEnable3G {    return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable); } 

在stackoverflow上有个问答介绍了一些关于Reachability的用法:点击查看


参考:
http://witcheryne.iteye.com/blog/1879827
http://oncerios.diandian.com/post/2013-06-28/40050041969
http://www.cocoachina.com/bbs/read.php?tid-31300.html
http://stackoverflow.com/questions/11177066/how-to-use-ios-reachability
0 0
原创粉丝点击