zoukankan      html  css  js  c++  java
  • (一二五)手机网络状态的监听

    对于一些需要与服务器进行长连接的App,需要对网络状态进行监控,当网络不佳时及时提醒用户,从而提高用户体验。通过苹果自带的框架和Reachability类可以实现网络状态改变的监听。

    要实现网络监听,按照下面的步骤进行。

    ①导入SystemConfiguration框架。

    ②通过Xcode的帮助文档搜索Reachability,打开样例工程,将其中的Reachability类的代码拷贝到自己的工程,有两个文件,如下图所示。

    ③创建对象,保存对象,添加监听和启动监听。

    注意reachabilityForInternetConnection才能用于wifi、3G、无网络三种状态。

    注意监听的名称为kReachabilityChangedNotification。

    - (void)viewDidLoad{
        
        [super viewDidLoad];
        Reachability *wifiReach = [Reachability reachabilityForInternetConnection];
        _wifiReach = wifiReach;
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange:) name:kReachabilityChangedNotification object:nil];
        [wifiReach startNotifier];
        
    }
    ④在监听的回调中拿到状态判断。

    注意要实现三种网络状态,要用真机来调试。

    - (void)networkStateChange:(NSNotification *)nof{
        
        switch (self.wifiReach.currentReachabilityStatus) {
            case ReachableViaWiFi:
                NSLog(@"wifi");
                break;
            case ReachableViaWWAN:
                NSLog(@"移动数据");
                break;
            case NotReachable:
                NSLog(@"无网络");
                break;
        }
        
    }
    ⑤在控制器销毁时,一定要记得移除监听。
    - (void)dealloc{
        
        [self.wifiReach stopNotifier];
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        
    }

  • 相关阅读:
    POJ 3672 水题......
    POJ 3279 枚举?
    STL
    241. Different Ways to Add Parentheses
    282. Expression Add Operators
    169. Majority Element
    Weekly Contest 121
    927. Three Equal Parts
    910. Smallest Range II
    921. Minimum Add to Make Parentheses Valid
  • 原文地址:https://www.cnblogs.com/aiwz/p/6154040.html
Copyright © 2011-2022 走看看