【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
- 【iOS开发】---- Reachability 网络监测
- iOS开发实时监测网络状态Reachability
- iOS网络开发:监测当前网络状态,Reachability
- iOS 监测网络状态(Reachability)
- iOS 网络状态监测。Reachability 使用
- iOS之 网络连接监测框架 Reachability
- Reachability监测网络环境
- 使用Reachability网络监测
- 网络状态监测Reachability
- IOS网络开发(Reachability)
- iOS网络状态监测之Reachability的使用
- IOS SCNetworkReachability和Reachability监测网络连接状态
- iOS开发:网络监测
- iOS开发实践之网络检测Reachability
- iOS开发--监测网络变化
- iOS 开发 网络实时监测
- iOS开发--监测网络状态
- IOS判断网络Reachability
- HDU 1114 Piggy-Bank (完全背包)
- Unity3d之Bug收集
- 关于java面向对象的理解
- yarn2.2.0安装问题记录
- 软件架构学习小结
- 【iOS开发】---- Reachability 网络监测
- 阿里电面题:输出给定字符串的全部连续子串
- tomcat源码分析
- python实现聊天室--C/S模式
- activity的使用(十三):操作扩展卡
- Kinect for Windows SDK开发入门(二):基础知识 上
- Mark~
- linux下查找进程及终止进程操作的相关命令
- Java数组