iOS:Reachability网络监听

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

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

//  ViewController.m
//  网络状态监听
//
//  Created by ma c on 16/01/29.
//  Copyright (c) 2016年 XYQ. All rights reserved.
//

#import "ViewController.h"
#import "Reachability.h"

@interface ViewController ()
@property (strong,nonatomic)Reachability *reachablity;//网络监听对象
@property (assign,nonatomic)BOOL isReachable;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //1.创建网络监听通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];

    //2.创建Reachability监听对象
    Reachability *reachablity = [Reachability reachabilityWithHostName:@"localhost"];
    self.reachablity = reachablity;
    
    //3.开始监听
    [self.reachablity startNotifier];
}


//监听网络类型
-(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

技术分享

以上是关于iOS:Reachability网络监听的主要内容,如果未能解决你的问题,请参考以下文章

Reachability的使用

:iOS网络应用编程

IOS的网络环境判断

使用Reachability实时监测网络连通性

iOS开发实践之网络检測Reachability

iOS开发实践之网络检测Reachability