IOS-网络(监听网络状态)

时间:2023-03-09 01:09:02
IOS-网络(监听网络状态)
 //
// BWNetWorkTool.h
// IOS_0131_检测网络状态
//
// Created by ma c on 16/1/31.
// Copyright © 2016年 博文科技. All rights reserved.
// #import <Foundation/Foundation.h> @interface BWNetWorkTool : NSObject
///是否是WiFi
+ (BOOL)isEnableWiFi;
///是否是3G
+ (BOOL)isEnable3G; @end //
// BWNetWorkTool.m
// IOS_0131_检测网络状态
//
// Created by ma c on 16/1/31.
// Copyright © 2016年 博文科技. All rights reserved.
// #import "BWNetWorkTool.h"
#import "Reachability.h" @implementation BWNetWorkTool //是否是WiFi
+ (BOOL)isEnableWiFi
{
return [[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] !=NotReachable;
}
//是否是3G
+ (BOOL)isEnable3G
{
return [[Reachability reachabilityForInternetConnection] currentReachabilityStatus] !=NotReachable;
} @end
 //
// ViewController.m
// IOS_0131_检测网络状态
//
// Created by ma c on 16/1/31.
// Copyright © 2016年 博文科技. All rights reserved.
// #import "ViewController.h"
#import "Reachability.h"
#import "BWNetWorkTool.h" @interface ViewController () @property (nonatomic, strong) Reachability *reachability; @end @implementation ViewController
/*
检测网络状态
1.在网络应用中,需要对用户设备的网络状态进行实时监控,目的:
a.让用户了解自己的网络状态,防止一些误会(怪应用无能)
b.根据用户的网络状态进行智能处理,节省用户流量,提高用户体验
WIFI/3G/4G网络:自动下载高清图片
低速网络:只能下载缩略图
没有网络:智能显示离线的缓存数据
c.苹果官方提供了一个叫Reachability的示例程序,便于开发者检测网络状态
https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip 2.Reachability的使用步骤
1>添加框架SystemConfiguration.framework
2>添加源代码
3>包含头文件 - #import "Reachability.h" 3.常见用法
1>是否是WiFi
+ (BOOL)isEnableWiFi
{
return [[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] !=NotReachable;
}
2>是否是3G
+ (BOOL)isEnable3G
{
return [[Reachability reachabilityForInternetConnection] currentReachabilityStatus] !=NotReachable;
}
*/ - (void)viewDidLoad {
[super viewDidLoad]; //监听网络状态发生改变通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil]; //获得Reachability对象
self.reachability = [Reachability reachabilityForInternetConnection]; //开始监控
[self.reachability startNotifier]; // //获取Reachability对象
// Reachability *wifi = [Reachability reachabilityForLocalWiFi];
// //获取Reachability对象的当前网络状态
// NetworkStatus wifiStatus = wifi.currentReachabilityStatus;
//
// if (wifiStatus !=NotReachable) {
// NSLog(@"wifi");
// } } - (void)networkStateChange
{
NSLog(@"网络状态改变了");
[self changeNetworkState];
} - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self changeNetworkState];
} - (void)changeNetworkState
{
if ([BWNetWorkTool isEnableWiFi]) {
NSLog(@"WiFi环境");
}else if ([BWNetWorkTool isEnable3G]){
NSLog(@"手机自带网络");
}else{
NSLog(@"没有网络");
}
} - (void)dealloc
{
[self.reachability stopNotifier];
[[NSNotificationCenter defaultCenter] removeObserver:self];
} @end