zoukankan      html  css  js  c++  java
  • iOS:Reachability网络监听

    iOS利用Reachability确认网络环境3G/WIFI

    开发Web等网络应用程序的时候,需要确认网络环境,连接情况等信息。如果没有处理它们,是不会通过Apple的审查的,一般情况下,可以把网络监听放在程序启动时执行。

    Apple 的 例程 Reachability 中介绍了取得/检测网络状态的方法。在你的程序中使用 Reachability 只须将该例程中的 Reachability.h 和 Reachability.m 拷贝到你的工程中。如下图:

    我们来看看Reachability.h文件中的具体内容:

    #import <Foundation/Foundation.h>
    #import <SystemConfiguration/SystemConfiguration.h>
    
    //! Project version number for MacOSReachability.
    FOUNDATION_EXPORT double ReachabilityVersionNumber;
    
    //! Project version string for MacOSReachability.
    FOUNDATION_EXPORT const unsigned char ReachabilityVersionString[];
    
    /** 
     * Create NS_ENUM macro if it does not exist on the targeted version of iOS or OS X.
     *
     * @see http://nshipster.com/ns_enum-ns_options/
     **/
    #ifndef NS_ENUM
    #define NS_ENUM(_type, _name) enum _name : _type _name; enum _name : _type
    #endif
    
    extern NSString *const kReachabilityChangedNotification;
    
    //但前网络类型
    typedef NS_ENUM(NSInteger, NetworkStatus) {
        // Apple NetworkStatus Compatible Names.
        NotReachable = 0,
        ReachableViaWiFi = 2,
        ReachableViaWWAN = 1
    };
    
    @class Reachability;
    
    typedef void (^NetworkReachable)(Reachability * reachability);
    typedef void (^NetworkUnreachable)(Reachability * reachability);
    typedef void (^NetworkReachability)(Reachability * reachability, SCNetworkConnectionFlags flags);
    
    
    @interface Reachability : NSObject
    
    @property (nonatomic, copy) NetworkReachable    reachableBlock;
    @property (nonatomic, copy) NetworkUnreachable  unreachableBlock;
    @property (nonatomic, copy) NetworkReachability reachabilityBlock;
    
    @property (nonatomic, assign) BOOL reachableOnWWAN;
    
    
    //类方法创建网络监听对象
    +(instancetype)reachabilityWithHostname:(NSString*)hostname;
    // This is identical to the function above, but is here to maintain
    //compatibility with Apples original code. (see .m)
    +(instancetype)reachabilityWithHostName:(NSString*)hostname;
    +(instancetype)reachabilityForInternetConnection;
    +(instancetype)reachabilityWithAddress:(void *)hostAddress;
    +(instancetype)reachabilityForLocalWiFi;
    
    
    //实例方法传附件网络监听对象
    -(instancetype)initWithReachabilityRef:(SCNetworkReachabilityRef)ref;
    
    -(BOOL)startNotifier;     //开始监听网络
    -(void)stopNotifier;      //停止监听网络
    
    -(BOOL)isReachable;        //是否没有网
    -(BOOL)isReachableViaWWAN; //是否使自带的网络
    -(BOOL)isReachableViaWiFi; //是否是WIFI
    
    
    
    // WWAN may be available, but not active until a connection has been established.
    // WiFi may require a connection for VPN on Demand.
    -(BOOL)isConnectionRequired; // Identical DDG variant.
    -(BOOL)connectionRequired; // Apple's routine.
    // Dynamic, on demand connection?
    -(BOOL)isConnectionOnDemand;
    // Is user intervention required?
    -(BOOL)isInterventionRequired;
    
    
    -(NetworkStatus)currentReachabilityStatus;     //获取当前网络状态
    -(SCNetworkReachabilityFlags)reachabilityFlags;//
    -(NSString*)currentReachabilityString;//当前网络字符串
    -(NSString*)currentReachabilityFlags; //当前网络标识
    
    @end

    下面我们用代码实现一下对自己主机的网络的监听

    方法一:直接使用Reachability这两个文件

    //  网络状态监听
    //
    //  Created by ma c on 16/01/29.
    //  Copyright (c) 2016年 XYQ. All rights reserved.
    //
    #import "AppDelegate.h"
    #import "Reachability.h"
    @interface AppDelegate ()
    @property(nonatomic,strong)Reachability *reachability; //网络监听对象
    @end
    
    @implementation AppDelegate
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
        //创建网络监听
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil];
        //创建网络监听对象
        self.reachability = [Reachability reachabilityForInternetConnection];
        //self.reachablity = [Reachability reachabilityWithHostName:@"localhost"]; //本机网络
        //开始检测
        [self.reachability startNotifier];
    
        return YES;
    }
    //监听网络类型
    -(void)NetWorkState
    {
        if ([self.reachablity isReachableViaWiFi]) {
            NSLog(@"是WIFI");
        }
        else if([self.reachablity isReachableViaWWAN]){
            NSLog(@"是WWAN");
        }
        else{
            NSLog(@"没有网");
        }
    }
    
    
    //网络链接改变时会调用的方法
    -(void)reachabilityChanged:(NSNotification *)note
    {
        [self NetWorkState];
        
        Reachability *currReach = [note object];
        NSParameterAssert([currReach isKindOfClass:[Reachability class]]);
        
        //对连接改变做出响应处理动作
        NetworkStatus status = [currReach currentReachabilityStatus];
        //如果没有连接到网络就弹出提醒实况
        self.isReachable = YES;
        if(status == NotReachable)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接异常" message:@"暂无法访问" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            self.isReachable = NO;
        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接信息" message:@"网络连接正常" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            self.isReachable = YES;
        }
    }
    
    -(void)dealloc
    {
        //停止监听,并移除通知
        [self.reachablity stopNotifier];
        [[NSNotificationCenter defaultCenter]removeObserver:self];
    }
    @end

    输出结果如下:我的电脑连接的就是WIFI

    2016-01-29 16:20:18.779 网络状态监听[4854:325480] 是WIFI

    方法二:使用第三方库AFNetworing封装的网络监听方法,创建网络监听管理者进行监听

    如何使用AFNetworking做网络监控呢?AFNetworkReachabilityManager这个类中自带着监听网络的方法,同时AFNetworkReachabilityManager还拥有一个枚举,代表着网络状况.

    typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) {
    
    AFNetworkReachabilityStatusUnknown = -1,//未识别的网络
    
    AFNetworkReachabilityStatusNotReachable = 0,//不可达的网络(未连接)
    
    AFNetworkReachabilityStatusReachableViaWWAN = 1,//2G,3G,4G...
    
    AFNetworkReachabilityStatusReachableViaWiFi = 2,//wifi网络
    
    };
    下面进行监听:
    #import "AppDelegate.h"
    #import <AFNetworking/AFNetworkReachabilityManager.h>
    
    @interface AppDelegate ()
    
    @property(nonatomic,strong)AFNetworkReachabilityManager *reachabilityManager;
    
    @end
    
    @implementation AppDelegate
    
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
        //创建网络监控对象
        self.reachabilityManager = [AFNetworkReachabilityManager sharedManager];
    
    
        //设置监听
        [_reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            switch (status) {
                case AFNetworkReachabilityStatusUnknown:
                    NSLog(@"未识别的网络");
                    break;
    
                case AFNetworkReachabilityStatusNotReachable:
                    NSLog(@"不可达的网络(未连接)");
                    break;
    
                case AFNetworkReachabilityStatusReachableViaWWAN:
                    NSLog(@"2G,3G,4G...的网络");
                    break;
    
                case AFNetworkReachabilityStatusReachableViaWiFi:
                    NSLog(@"wifi的网络");
                    break;
                default:
                    break;
            }
        }];
    
        //开始监听网络状况.
        [_reachabilityManager startMonitoring];
    
        return YES;
    }
    
    
    -(void)dealloc{
    
        //停止监听网络状况.
        [_reachabilityManager stopMonitoring];
    
    }
    总结:与Reachability相比之下,AFNetworking是不是代码更加的简练呢?AFNetworking其实封装了Reachability,使我们的代码更加的简单易上手.
     
  • 相关阅读:
    类与对象
    《大道至简》第三章读后感
    动手动脑及课后作业
    课程作业一
    第三周学习进度条
    软件工程个人作业02
    第二周学习进度条
    软件工程个人作业01(2)
    软件工程个人作业01
    登录界面
  • 原文地址:https://www.cnblogs.com/XYQ-208910/p/5169362.html
Copyright © 2011-2022 走看看