• Rechability的简单使用


    AppDelegate.m

    #import "AppDelegate.h"
    #import "Reachability.h"
    
    @interface AppDelegate ()
    
    @property (nonatomic, strong) Reachability *reachability;
    
    @end
    
    @implementation AppDelegate
    
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        // 监听网络状态的改变
        [self networkChange];
        
        return YES;
    }
    
    // 监听网络变化
    - (void)networkChange
    {
        // 开启网络状况的监听通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
        // 监听的链接
        self.reachability = [Reachability reachabilityWithHostName:@"www.baidu.com"];
        // 开始监听, 会启动一个Runloop
        [self.reachability startNotifier];
    }
    
    // 网络链接改变时会调用的方法
    - (void)reachabilityChanged:(NSNotification *)note
    {
        // 通过通知对象获取被监听的Reachability对象
        Reachability *currReach = [note object];
        NSAssert([currReach isKindOfClass:[Reachability class]], @"非Reachability类");
        
        //对连接改变做出响应处理动作
        NetworkStatus status = [currReach currentReachabilityStatus];
        
        //如果没有连接到网络就提醒实况
        if(status == NotReachable) {
            NSLog(@"AppDelegate - 网络连接异常");
            [[NSNotificationCenter defaultCenter] postNotificationName:@"networkChangeNotification" object:nil userInfo:@{@"networkStatusKey" : @(NO)}];
        } else {
            NSLog(@"AppDelegate - 网络连接正常");
            [[NSNotificationCenter defaultCenter] postNotificationName:@"networkChangeNotification" object:nil userInfo:@{@"networkStatusKey" : @(YES)}];
        }
    }
    
    @end

    ViewController.m

    #import "ViewController.h"
    
    @interface ViewController ()
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        // 监听网络状态
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkChange:) name:@"networkChangeNotification" object:nil];
    }
    
    - (void)dealloc
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    
    - (void)networkChange:(NSNotification *)notification
    {
        NSString *status = notification.userInfo[@"networkStatusKey"];
        
        if (status.boolValue) {         // 断网切换为正常状态
            NSLog(@"断网切换为正常状态");
        } else {                        // 正常切换为断网状态
            NSLog(@"正常切换为断网状态");
        }
    }
    
    @end

    Demo:

    https://github.com/RinpeChen/RechabilityDemoByRinpe

  • 相关阅读:
    hdu acm 2639背包问题,这题很经典啊~~~
    hdu acm 2191
    qt中实现区域反白效果
    解决pythonxml 模块 在ubuntu karmic中找不到的问题
    Python正则表达式操作指南
    webkit 资料
    标点符号的英语名称
    ubuntu设置分辨率
    如何绑定多个action到一个slot
    改注册表,实现像迅雷一样的自定义url
  • 原文地址:https://www.cnblogs.com/Rinpe/p/5048843.html
Copyright © 2020-2023  润新知