zoukankan      html  css  js  c++  java
  • iOS网络检测

    使用之前请从Apple网站下载示例:点此下载

    Reachability 中定义了3种网络状态:

    typedef enum : NSInteger {
        NotReachable = 0,//无网络
        ReachableViaWiFi,//wifi
        ReachableViaWWAN//3g
    } NetworkStatus;

    比如检测某一特定站点的接续状况,可以使用下面的代码:

        Reachability *r = [Reachability reachabilityWithHostName:@"www.apple.com"];
        switch ([r currentReachabilityStatus]) {
            case NotReachable:
                // 没有网络连接
                NSLog(@"没有网络连接");
                break;
            case ReachableViaWWAN:
                NSLog(@"使用3g网络");
                // 使用3G网络
                break;
            case ReachableViaWiFi:
                NSLog(@"使用wifi网络");
                // 使用WiFi网络
                break;
        }

    检测当前网络环境:

    // 是否wifi
    + (BOOL) IsEnableWIFI {
        return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
    }
    
    // 是否3G
    + (BOOL) IsEnable3G {
        return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);
    }

    连接状态实时通知:

    #import <UIKit/UIKit.h>
    #import "Reachability.h"
    @interface AppDelegate : UIResponder  <UIApplicationDelegate> {
        Reachability  *hostReach;
    }
    @property (strong, nonatomic) UIWindow *window;
    
    
    @end
    - (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:@"提示"
                                                            message:@"你的网络已断开连接"
                                                           delegate:nil
                                                  cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
        }
    }
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        // 监测网络情况
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(reachabilityChanged:)
                                                     name: kReachabilityChangedNotification
                                                   object: nil];
        hostReach = [Reachability reachabilityWithHostName:@"www.google.com"];//可以以多种形式初始化
        [hostReach startNotifier];//开始监听,会启动一个run loop
        return YES;
    }
     
  • 相关阅读:
    python学习随笔--string[:]
    年少时读不懂 天龙八部,如今读懂已过少年
    web安全测试随笔
    纪录jmeter loop controller 使用中的一个坑
    移动设备覆盖统计数据源
    jmeter and postman
    web测试----http状态码
    转自莫某的java学习计划
    jquery实现页面加载时删除特定class 的div内前三个字符
    js学习
  • 原文地址:https://www.cnblogs.com/hxwj/p/4461885.html
Copyright © 2011-2022 走看看