zoukankan      html  css  js  c++  java
  • 监测网络状态

    监测网络状态

    转自 http://www.cnblogs.com/wendingding/p/3950114.html#

    有些许修改

    #import "YYViewController.h"
    #import "Reachability.h"

    @interface YYViewController ()
    @property (nonatomic, strong) Reachability *conn;
    @end

    @implementation YYViewController

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil];
        self.conn = [Reachability reachabilityForInternetConnection];
        [self.conn startNotifier];

      [[NSNotificationCenter defaultCenter] postNotificationName:kReachabilityChangedNotification object:nil];//发通知(增加)
    }

    - (void)dealloc
    {
        [self.conn stopNotifier];
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }

    - (void)networkStateChange
    {
        [self checkNetworkState];
    }

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {

    }

    - (void)checkNetworkState
    {
        // 1.检测wifi状态
        Reachability *wifi = [Reachability reachabilityForLocalWiFi];
        
        // 2.检测手机是否能上网络(WIFI3G2.5G)
        Reachability *conn = [Reachability reachabilityForInternetConnection];
        
        // 3.判断网络状态
        if ([wifi currentReachabilityStatus] != NotReachable) { // 有wifi
            NSLog(@"有wifi");
            
        } else if ([conn currentReachabilityStatus] != NotReachable) { // 没有使用wifi, 使用手机自带网络进行上网
            NSLog(@"使用手机自带网络进行上网");
            
        } else { // 没有网络
            
            NSLog(@"没有网络");

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                            message:@"没有网络请检查网络设置"
                                                           delegate:nil
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil];
            [alert show];
            alert = nil;
        }
    }
    @end

    // 用WIFI
    // [wifi currentReachabilityStatus] != NotReachable
    // [conn currentReachabilityStatus] != NotReachable

    // 没有用WIFI, 只用了手机网络
    // [wifi currentReachabilityStatus] == NotReachable
    // [conn currentReachabilityStatus] != NotReachable

    // 没有网络
    // [wifi currentReachabilityStatus] == NotReachable
    // [conn currentReachabilityStatus] == NotReachable

    这只是网络状态改变时就会检测到,但一开始就没网络的状态下需要自己判断再提示信息

  • 相关阅读:
    突袭HTML5之HTML元素扩展(上) 新增加的元素
    DIV常见任务(下) 变身为编辑器
    突袭HTML5之Javascript API扩展3 本地存储
    突袭HTML5之Javascript API扩展5 其他扩展
    DIV常见任务(上) 常规任务
    突袭HTML5之HTML元素扩展(下) 增强的Form元素
    突袭HTML5之WebGL 3D概述(下) 借助类库开发
    突袭HTML5之Javascript API扩展4 拖拽
    突袭HTML5之Javascript API扩展1 Web Worker异步执行
    突袭HTML5之Javascript API扩展2 地理信息服务
  • 原文地址:https://www.cnblogs.com/berry1124/p/4818872.html
Copyright © 2011-2022 走看看