首页 > 代码库 > 使用Reachability实时监测网络连通性

使用Reachability实时监测网络连通性

在开发ios应用是我匀经常要使用网络,还得监控网络的连接情况,当网络发生改变时进行对应的事件处理工作。下面就讲解一下利用Reachability进行网络边连接情况监测的使用方法。

要使用Reachability进行网络监控必须先导进Reachability.h和Reachability.m两个方件。

在.h文件中声明一个全局的Reachability类,代码如下:

#import

#import "Reachability.h"

@interface AppDelegate : UIResponder {

Reachability *hostReach;

}

@property (strong, nonatomic) UIWindow *window;

@end

在.m文件中加入对应的代码

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

// Override point for customization after application launch.

//监测网络情况

[[NSNotificationCenter defaultCenter] addObserver:self

selector:@selector(reachabilityChanged:)

name: kReachabilityChangedNotification

object: nil];

//初始化Reachability类,并添加一个监测的网址。

hostReach = [Reachability reachabilityWithHostName:@"http://blog.sina.com.cn/u/2526279194"];

//开始监测

[hostReach startNotifier];

self.window.backgroundColor = [UIColor whiteColor];

[self.window makeKeyAndVisible];

return YES;

}

#pragma mark - 监测网络情况,当网络发生改变时会调用

- (void)reachabilityChanged:(NSNotification *)note {

Reachability* curReach = [note object];

NSParameterAssert([curReach isKindOfClass: [Reachability class]]);

NetworkStatus status = [curReach currentReachabilityStatus];

if (status == NotReachable) {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil

message:@"NotReachable"

delegate:nil

cancelButtonTitle:@"YES" otherButtonTitles:nil];

[alert show];

alert = nil;

}

}

使用Reachability实时监测网络连通性