一 示例代码
需要先把第三方Reachability下载导入到工程中 下载网址 https://github.com/tonymillion/Reachability
1 封装网络工具类 NetworkTool
//
// NetworkTool.h
// 网络状态检测
//
// Created by lovestarfish on 15/11/7.
// Copyright © 2015年 S&G. All rights reserved.
// #import <Foundation/Foundation.h> @interface NetworkTool : NSObject /**
* 是否WIFI
*/
+ (BOOL)IsEnableWIFI; /**
* 是否3G
*/
+ (BOOL)IsEnable3G; @end
//
// NetworkTool.m
// 网络状态检测
//
// Created by lovestarfish on 15/11/7.
// Copyright © 2015年 S&G. All rights reserved.
// #import "NetworkTool.h"
#import "Reachability.h" @implementation NetworkTool
//是否WIFI
+ (BOOL)IsEnableWIFI {
return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
} //是否3G
+ (BOOL)IsEnable3G {
return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);
} @end
2 在viewController类中导入我们封装好的网络工具类
//
// RootViewController.m
// 网络状态检测
//
// Created by lovestarfish on 15/11/7.
// Copyright © 2015年 S&G. All rights reserved.
// #import "RootViewController.h"
#import "Reachability.h"
#import "NetworkTool.h" @interface RootViewController () @property (nonatomic,strong) Reachability *reachability; @end @implementation RootViewController - (void)viewDidLoad {
[super viewDidLoad]; //监听网络状态发生改变的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChanged) name:kReachabilityChangedNotification object:nil]; //获得Reachability对象
self.reachability = [Reachability reachabilityForInternetConnection]; //开始监控网络
[self.reachability startNotifier];
} /**
* 网络状态发生改变时
*/
- (void)networkStateChanged {
[self checkNetworkState];
} /**
* 检测当前网络状态
*/
- (void)checkNetworkState {
if ([NetworkTool IsEnable3G]) {
[self presentAlertController:@"已经连接WIFI"];
NSLog(@"WIFi环境");
} else if ([NetworkTool IsEnable3G] ) {
[self presentAlertController:@"当前为手机自带网络"];
NSLog(@"手机自带网络");
} else {
[self presentAlertController:@"网络不可用"];
NSLog(@"没有网络");
}
} /**
* 网络发生变化时以弹出框消息提示用户
*/
- (void)presentAlertController:(NSString *)message {
UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { }];
[alertC addAction:action];
[self presentViewController:alertC animated:YES completion:nil];
} /**
* 在合适的时机移除通知
*/
- (void)dealloc {
[self.reachability stopNotifier];
[[NSNotificationCenter defaultCenter] removeObserver:self];
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
} @end
二 实现效果