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;

    }

    }

  • 相关阅读:
    Cocos2dx-demo演示项目:Part2
    利用Python抓取亚马逊评论列表数据
    Cocos2dx-demo演示项目:Part1
    正则表达式匹配原理
    js正则函数中test和match的区别
    【别人家的孩子系列之】浅析正则表达式—(原理篇)
    JS 获取浏览器窗口大小
    javascript的insertBefore、insertAfter和appendChild简单介绍
    javascript 限制字符串字数换行 带BUG
    一行一行分析JQ源码学习笔记-06
  • 原文地址:https://www.cnblogs.com/CJH5209/p/6027434.html
Copyright © 2011-2022 走看看