您的位置:首页 > 理论基础 > 计算机网络

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

2014-03-15 15:18 267 查看
在开发的过程中,我们需要检测网络状态,比如当前网络状态(连接,断开),网络环境(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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: