//
// NetStateManage.h
//
// Created by miniu on 15/11/24.
// Copyright © 2015年 mini. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Reachability.h"
@protocol NetStateManageDelegate <NSObject>
@optional
-(void)networkStatusChange:(NetworkStatus)networkStatus;
@end
@interface NetStateManage : NSObject
@property (nonatomic,weak)id <NetStateManageDelegate>delegate;
+ (NetStateManage *)shareInstance;
//当前的网络状态
- (NetworkStatus)currentNetworkStatus;
@end
//
// NetStateManage.m
//
// Created by miniu on 15/11/24.
// Copyright © 2015年 mini. All rights reserved.
//
#import "NetStateManage.h"
@interface NetStateManage ()
{
Reachability *reachability;
NetworkStatus hostNetStatus;
}
@end
@implementation NetStateManage
- (instancetype)init
{
self = [super init];
if (self) {
//使用Reachability
[self useReachability];
}
return self;
}
- (void)useReachability{
// 监听网络状态改变的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil];
// 创建Reachability
reachability = [Reachability reachabilityForInternetConnection];
// 开始监控网络(一旦网络状态发生改变, 就会发出通知kReachabilityChangedNotification)
[reachability startNotifier];
}
// 处理网络状态改变
- (void)networkStateChange
{
// 1.检测wifi状态
Reachability *wifi = [Reachability reachabilityForLocalWiFi];
// 2.检测手机是否能上网络(WIFI\3G\2.5G)
Reachability *conn = [Reachability reachabilityForInternetConnection];
// 3.判断网络状态
if ([wifi currentReachabilityStatus] != NotReachable) { // 有wifi
NSLog(@"有wifi");
hostNetStatus=ReachableViaWiFi;
} else if ([conn currentReachabilityStatus] != NotReachable) { // 没有使用wifi, 使用手机自带网络进行上网
NSLog(@"使用手机自带网络进行上网");
hostNetStatus=ReachableViaWWAN;
}else { // 没有网络
NSLog(@"没有网络");
hostNetStatus=NotReachable;
}
if ([self.delegate respondsToSelector:@selector(networkStatusChange:)]) {
[self.delegate networkStatusChange:hostNetStatus];
}
}
+ (NetStateManage *)shareInstance
{
static NetStateManage *hardwareManager=nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
hardwareManager=[[self alloc] init];
});
return hardwareManager;
}
//返回当前的网络状态
- (NetworkStatus)currentNetworkStatus
{
return [reachability currentReachabilityStatus];
}
@end