zoukankan      html  css  js  c++  java
  • 使用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;

    }

    }

  • 相关阅读:
    09-JS的事件流的概念(重点)
    08-jQuery的位置信息
    07-小米导航案例
    python-selector模块
    python--day9--异步IO、数据库、队列、缓存
    python--select多路复用socket
    python--gevent高并发socket
    python--协程
    python--进程锁、进程池
    python--多进程
  • 原文地址:https://www.cnblogs.com/CJH5209/p/6027434.html
Copyright © 2011-2022 走看看