博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
IOS开发网络篇—监测网络状态
阅读量:4688 次
发布时间:2019-06-09

本文共 2135 字,大约阅读时间需要 7 分钟。

iOS开发网络篇—监测网络状态

一、说明

在网络应用中,需要对用户设备的网络状态进行实时监控,有两个目的:

(1)让用户了解自己的网络状态,防止一些误会(比如怪应用无能)

(2)根据用户的网络状态进行智能处理,节省用户流量,提高用户体验

  WIFI\3G网络:自动下载高清图片

  低速网络:只下载缩略图

  没有网络:只显示离线的缓存数据

 

苹果官方提供了一个叫Reachability的示例程序,便于开发者检测网络状态

二、监测网络状态

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)viewDidLoad11 {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)dealloc20 {21     [self.conn stopNotifier];22     [[NSNotificationCenter defaultCenter] removeObserver:self];23 }24 25 - (void)networkStateChange26 {27     [self checkNetworkState];28 }29 30 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event31 {32 33 }34 35 - (void)checkNetworkState36 {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) { // 有wifi45         NSLog(@"有wifi");46         47     } else if ([conn currentReachabilityStatus] != NotReachable) { // 没有使用wifi, 使用手机自带网络进行上网48         NSLog(@"使用手机自带网络进行上网");49         50     } else { // 没有网络51         52         NSLog(@"没有网络");53     }54 }55 @end56 57 // 用WIFI58 // [wifi currentReachabilityStatus] != NotReachable59 // [conn currentReachabilityStatus] != NotReachable60 61 // 没有用WIFI, 只用了手机网络62 // [wifi currentReachabilityStatus] == NotReachable63 // [conn currentReachabilityStatus] != NotReachable64 65 // 没有网络66 // [wifi currentReachabilityStatus] == NotReachable67 // [conn currentReachabilityStatus] == NotReachable

转载于:https://www.cnblogs.com/MJC-IOS-2010/p/5466666.html

你可能感兴趣的文章
zTree async 动态参数处理
查看>>
Oracle学习之常见错误整理
查看>>
HTC Sensation G14开盒
查看>>
lock_sga引起的ksvcreate :process(m000) creation failed
查看>>
数据库插入数据乱码问题
查看>>
OVER(PARTITION BY)函数用法
查看>>
altium annotate 选项设置 complete existing packages
查看>>
【模式识别与机器学习】——SVM举例
查看>>
【转】IT名企面试:微软笔试题(1)
查看>>
IO流入门-第十章-DataInputStream_DataOutputStream
查看>>
DRF的分页
查看>>
Mysql 模糊匹配(字符串str中是否包含子字符串substr)
查看>>
IIS的ISAPI接口简介
查看>>
python:open/文件操作
查看>>
16 乘法口诀输出
查看>>
mac 常用地址
查看>>
鼠标经过切换图片
查看>>
流程控制 Day06
查看>>
Linux下安装Tomcat
查看>>
windows live writer 2012 0x80070643
查看>>