[iOS 多线程 & 网络 - 2.8] - 检测网络状态

时间:2021-12-15 23:36:26
A、说明
在网络应用中,需要对用户设备的网络状态进行实时监控,有两个目的:
(1)让用户了解自己的网络状态,防止一些误会(比如怪应用无能)
(2)根据用户的网络状态进行智能处理,节省用户流量,提高用户体验
  WIFI\3G网络:自动下载高清图片
  低速网络:只下载缩略图
  没有网络:只显示离线的缓存数据
苹果官方提供了一个叫Reachability的示例程序,便于开发者检测网络状态
https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip
 
注意:此功能只能用真机测试,iOS模拟器,一直都有wifi信号,即使关掉或者使用飞行模式.
 
B、监测网络状态
Reachability的使用步骤
添加框架SystemConfiguration.framework
包含头文件
#import "Reachability.h"
 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// 检测wifi状态
Reachability *wifiStatus = [Reachability reachabilityForLocalWiFi]; // 检测手机网络状态
Reachability *netStatus = [Reachability reachabilityForInternetConnection]; // 判断网络状态
if ([wifiStatus currentReachabilityStatus] != NotReachable) {
NSLog(@"正在使用wifi上网");
} else if ([netStatus currentReachabilityStatus] != NotReachable) {
NSLog(@"正在使用手机网络上网");
} else {
NSLog(@"没有网络");
}
}
C.实时监测网络状态
使用通知监控
网络状态类要发送通知给控制器
销毁控制器的时候一定要删除通知、停止发送消息
 //
// ViewController.m
// ReachabilityDemo
//
// Created by hellovoidworld on 15/1/28.
// Copyright (c) 2015年 hellovoidworld. All rights reserved.
// #import "ViewController.h"
#import "Reachability.h" @interface ViewController () @property(nonatomic, strong) Reachability *networkStatus; @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib. // 实时监控手机联网状态
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(detectNetworkStatus) name:kReachabilityChangedNotification object:nil]; // 开启通知发送
self.networkStatus = [Reachability reachabilityForInternetConnection];
[self.networkStatus startNotifier];
} - (void)dealloc {
// 停止发送通知
[self.networkStatus stopNotifier]; // 切记要删除通知
[[NSNotificationCenter defaultCenter] removeObserver:self];
} // 用WIFI
// [wifi currentReachabilityStatus] != NotReachable
// [conn currentReachabilityStatus] != NotReachable // 没有用WIFI, 只用了手机网络
// [wifi currentReachabilityStatus] == NotReachable
// [conn currentReachabilityStatus] != NotReachable // 没有网络
// [wifi currentReachabilityStatus] == NotReachable
// [conn currentReachabilityStatus] == NotReachable - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self detectNetworkStatus];
} - (void) detectNetworkStatus {
// 检测wifi状态
Reachability *wifiStatus = [Reachability reachabilityForLocalWiFi]; // 检测手机网络状态
Reachability *netStatus = [Reachability reachabilityForInternetConnection]; // 判断网络状态
if ([wifiStatus currentReachabilityStatus] != NotReachable) {
NSLog(@"正在使用wifi上网");
} else if ([netStatus currentReachabilityStatus] != NotReachable) {
NSLog(@"正在使用手机网络上网");
} else {
NSLog(@"没有网络");
}
} @end