iOS中判断网络是否联网

2016/03/26 15:41
阅读数 33

.h文件

#import <Foundation/Foundation.h>


@interface ReachbilityHelper : NSObject


+ (id)sharedReachbility;


/// Wi-Fi是否可用

+ (BOOL)isEnableWiFi;


/// 3G是否可用

+ (BOOL)isEnable3G;


///启动监听

- (void)startObserve;


///网络是否能够连接

- (BOOL)isConnectable;


///是否是Wi-Fi连接

- (BOOL)isWiFi;


///是否通过3g/gprs网络

- (BOOL)is3G;


@end



.m文件


#import "ReachbilityHelper.h"

#import <Reachability.h>


@interface ReachbilityHelper ()

{

    Reachability *hostReachablility;

    NetworkStatus statusNetwork;

}


@end


@implementation ReachbilityHelper


- (void)dealloc

{

    [[NSNotificationCenter defaultCenter] removeObserver:self];

}


+ (id)sharedReachbility

{

    static Reachability *instance;

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        instance = [[self alloc] init];

    });

    

    return instance;

}


- (void)startObserve

{

    //监测网络情况

    [[NSNotificationCenter defaultCenter] addObserver:self

                                             selector:@selector(reachabilityChanged:)

                                                 name: kReachabilityChangedNotification

                                               object: nil];

    hostReachablility = [Reachability reachabilityWithHostname:@"www.baidu.com"];

    [_hostReach startNotifier];

}


- (void)reachabilityChanged:(NSNotification *)note

{

    Reachability* curReach = [note object];

    NSParameterAssert([curReach isKindOfClass:[Reachability class]]);

    statusNetwork = [curReach currentReachabilityStatus];

}


// Wi-Fi是否可用

+ (BOOL)isEnableWiFi

{

    return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);

}


// 3G是否可用

+ (BOOL)isEnable3G

{

    return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);

}


//网络是否能够连接

- (BOOL)isConnectable

{

    return statusNetwork != NotReachable;

}


//是否是Wi-Fi连接

- (BOOL)isWiFi

{

    return statusNetwork == ReachableViaWiFi;

}


//是否通过3g/gprs网络

- (BOOL)is3G

{

    return statusNetwork == ReachableViaWWAN;

}



展开阅读全文
打赏
1
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
1
分享
返回顶部
顶部