一 示例代码
需要先把第三方Reachability下载导入到工程中 下载网址 /tonymillion/Reachability
1 封装网络工具类 NetworkTool
1 // 2 // NetworkTool.h 3 // 网络状态检测 4 // 5 // Created by lovestarfish on 15/11/7. 6 // Copyright © S&G. All rights reserved. 7 // 8 9 #import <Foundation/Foundation.h>10 11 @interface NetworkTool : NSObject12 13 /**14 * 是否WIFI15 */16 + (BOOL)IsEnableWIFI;17 18 /**19 * 是否3G20 */21 + (BOOL)IsEnable3G;22 23 @end
1 // 2 // NetworkTool.m 3 // 网络状态检测 4 // 5 // Created by lovestarfish on 15/11/7. 6 // Copyright © S&G. All rights reserved. 7 // 8 9 #import "NetworkTool.h"10 #import "Reachability.h"11 12 @implementation NetworkTool13 //是否WIFI14 + (BOOL)IsEnableWIFI {15return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);16 }17 18 //是否3G19 + (BOOL)IsEnable3G {20return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);21 }22 23 @end
2 在viewController类中导入我们封装好的网络工具类
1 // 2 // RootViewController.m 3 // 网络状态检测 4 // 5 // Created by lovestarfish on 15/11/7. 6 // Copyright © S&G. All rights reserved. 7 // 8 9 #import "RootViewController.h"10 #import "Reachability.h"11 #import "NetworkTool.h"12 13 @interface RootViewController ()14 15 @property (nonatomic,strong) Reachability *reachability;16 17 @end18 19 @implementation RootViewController20 21 - (void)viewDidLoad {22[super viewDidLoad];23 24//监听网络状态发生改变的通知25[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChanged) name:kReachabilityChangedNotification object:nil];2627//获得Reachability对象28self.reachability = [Reachability reachabilityForInternetConnection];2930//开始监控网络31[self.reachability startNotifier];32 }33 34 /**35 * 网络状态发生改变时36 */37 - (void)networkStateChanged {38[self checkNetworkState];39 }40 41 /**42 * 检测当前网络状态43 */44 - (void)checkNetworkState {45if ([NetworkTool IsEnable3G]) {46 [self presentAlertController:@"已经连接WIFI"];47 NSLog(@"WIFi环境");48} else if ([NetworkTool IsEnable3G] ) {49 [self presentAlertController:@"当前为手机自带网络"];50 NSLog(@"手机自带网络");51} else {52 [self presentAlertController:@"网络不可用"];53 NSLog(@"没有网络");54}55 }56 57 /**58 * 网络发生变化时以弹出框消息提示用户59 */60 - (void)presentAlertController:(NSString *)message {61UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];62UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {63 64}];65[alertC addAction:action];66[self presentViewController:alertC animated:YES completion:nil];67 }68 69 /**70 * 在合适的时机移除通知71 */72 - (void)dealloc {73[self.reachability stopNotifier];74[[NSNotificationCenter defaultCenter] removeObserver:self];75 }76 77 - (void)didReceiveMemoryWarning {78[super didReceiveMemoryWarning];79 }80 81 @end
二 实现效果
如果觉得《iOS开发 -------- 网络状态监测》对你有帮助,请点赞、收藏,并留下你的观点哦!