iOS开发网络篇—监测网络状态
2023-09-27 14:28:40 时间
iOS开发网络篇—监测网络状态
一、说明
在网络应用中,需要对用户设备的网络状态进行实时监控,有两个目的:
(1)让用户了解自己的网络状态,防止一些误会(比如怪应用无能)
(2)根据用户的网络状态进行智能处理,节省用户流量,提高用户体验
WIFI\3G网络:自动下载高清图片
低速网络:只下载缩略图
没有网络:只显示离线的缓存数据
苹果官方提供了一个叫Reachability的示例程序,便于开发者检测网络状态
https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip
二、监测网络状态
Reachability的使用步骤
添加框架SystemConfiguration.framework
添加源代码
包含头文件
#import "Reachability.h"
代码示例:
1 #import "YYViewController.h" 2 #import "Reachability.h" 3 4 @interface YYViewController () 5 @property (nonatomic, strong) Reachability *conn; 6 @end 7 8 @implementation YYViewController 9 10 - (void)viewDidLoad 11 { 12 [super viewDidLoad]; 13 14 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil]; 15 self.conn = [Reachability reachabilityForInternetConnection]; 16 [self.conn startNotifier]; 17 } 18 19 - (void)dealloc 20 { 21 [self.conn stopNotifier]; 22 [[NSNotificationCenter defaultCenter] removeObserver:self]; 23 } 24 25 - (void)networkStateChange 26 { 27 [self checkNetworkState]; 28 } 29 30 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 31 { 32 33 } 34 35 - (void)checkNetworkState 36 { 37 // 1.检测wifi状态 38 Reachability *wifi = [Reachability reachabilityForLocalWiFi]; 39 40 // 2.检测手机是否能上网络(WIFI\3G\2.5G) 41 Reachability *conn = [Reachability reachabilityForInternetConnection]; 42 43 // 3.判断网络状态 44 if ([wifi currentReachabilityStatus] != NotReachable) { // 有wifi 45 NSLog(@"有wifi"); 46 47 } else if ([conn currentReachabilityStatus] != NotReachable) { // 没有使用wifi, 使用手机自带网络进行上网 48 NSLog(@"使用手机自带网络进行上网"); 49 50 } else { // 没有网络 51 52 NSLog(@"没有网络"); 53 } 54 } 55 @end 56 57 // 用WIFI 58 // [wifi currentReachabilityStatus] != NotReachable 59 // [conn currentReachabilityStatus] != NotReachable 60 61 // 没有用WIFI, 只用了手机网络 62 // [wifi currentReachabilityStatus] == NotReachable 63 // [conn currentReachabilityStatus] != NotReachable 64 65 // 没有网络 66 // [wifi currentReachabilityStatus] == NotReachable 67 // [conn currentReachabilityStatus] == NotReachable
相关文章
- iOS开发网络篇—数据缓存
- iOS开发网络篇—NSURLConnection基本使用
- iOS开发网络数据之AFNetworking使用
- IOS网络编程:HTTP
- iOS网络
- iOS关键组件iBoot源代码泄露
- iOS开发网络篇—数据安全
- iOS开发网络篇—网络请求(HTTP协议)小结(转)
- iOS 获取网络状态
- iOS UITabBarController的使用
- iOS新特性: iOS10.3教你如何动态更换APP图标?(后台切换) 韩俊强的博客
- iOS中 WGAFN_网络监控 技术分享
- 76款流行iOS应用易受中间人攻击,1800万用户受影响
- iOS系统网络抓包方法
- ios开发证书CSR文件、CER文件、P12文件,mobileprovition许可文件的用途
- iOS 减法计算器
- 李洪强iOS经典面试题141-报错警告调试
- 李洪强iOS开发之带placeHolder的Textview
- iOS开发网络篇—发送json数据给服务器以及多值参数
- iOS开发网络篇—使用ASI框架进行文件下载
- iOS开发网络篇—GET请求和POST请求
- iOS开发网络篇—HTTP协议
- iOS开发25个性能调优技巧
- iOS开发Swift篇—(六)流程控制
- iOS开发之--NSPredicate
- iOS-在AFN基础上进行网络请求的封装
- iOS-MJExtension的使用