美文网首页
iOS开发网络篇—监测网络状态

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

作者: 李sir35 | 来源:发表于2016-08-16 17:06 被阅读75次

一、说明

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

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

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

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

低速网络:只下载缩略图

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

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

https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip

二、监测网络状态

Reachability的使用步骤

添加框架SystemConfiguration.framework

添加源代码

包含头文件

#import "Reachability.h"

代码示例:

#import "YYViewController.h"

#import "Reachability.h"

@interface YYViewController ()

@property (nonatomic, strong) Reachability *conn;

@end

@implementation YYViewController

- (void)viewDidLoad

{

[super viewDidLoad];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil];

self.conn = [Reachability reachabilityForInternetConnection];

[self.conn startNotifier];

}

- (void)dealloc

{

[self.conn stopNotifier];

[[NSNotificationCenter defaultCenter] removeObserver:self];

}

- (void)networkStateChange

{

[self checkNetworkState];

}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

}

- (void)checkNetworkState

{

// 1.检测wifi状态

Reachability *wifi = [Reachability reachabilityForLocalWiFi];

// 2.检测手机是否能上网络(WIFI\3G\2.5G)

Reachability *conn = [Reachability reachabilityForInternetConnection];

// 3.判断网络状态

if ([wifi currentReachabilityStatus] != NotReachable) { // 有wifi

NSLog(@"有wifi");

} else if ([conn currentReachabilityStatus] != NotReachable) { // 没有使用wifi, 使用手机自带网络进行上网

NSLog(@"使用手机自带网络进行上网");

} else { // 没有网络

NSLog(@"没有网络");

}

}

@end

// 用WIFI

// [wifi currentReachabilityStatus] != NotReachable

// [conn currentReachabilityStatus] != NotReachable

// 没有用WIFI, 只用了手机网络

// [wifi currentReachabilityStatus] == NotReachable

// [conn currentReachabilityStatus] != NotReachable

// 没有网络

// [wifi currentReachabilityStatus] == NotReachable

// [conn currentReachabilityStatus] == NotReachable

相关文章

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

    一、说明 在网络应用中,需要对用户设备的网络状态进行实时监控,有两个目的: (1)让用户了解自己的网络状态,防止一...

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

    一、说明 在网络应用中,需要对用户设备的网络状态进行实时监控,有两个目的: (1)让用户了解自己的网络状态,防止一...

  • 判断设备是否真正的连接互联网

    在iOS中监测网络状态有好几种方式,详情点击这里。但是在一般的网络监测都只是能够监测本地的网络状态,而真实的网络可...

  • iOS开发 监测网络状态

    一、说明 在网络应用中,需要对用户设备的网络状态进行实时监控,有两个目的: (1)让用户了解自己的网络状态,防止一...

  • AFNetworking3.0网络状态监测<二>

    SystemConfiguration网络监测 网络状态监测使用SystemConfiguration这个API ...

  • iOS进阶之网络--网络状态监测

    Reachability简介 很多应用中都会涉及对用户手机所在网络环境(数据、WiFi、无网络)的监测,在不同的网...

  • iOS监测网络状态

    .#### - 可以利用AFNetworking实现监测手机网络状态的功能 创建监听管理者 开始进行监控 判断当前...

  • iOS监测网络状态

    1.通过AFNetworking的AFNetworkReachabilityManager对象 监听网络方法 调用...

  • AFNetworking 3.0的使用

    下面介绍一下iOS开发中几种最常用到的AFNetworking方法。 一、实时监测网络状态 可以看到很多app都会...

  • NSURLSession

    iOS开发网络篇

网友评论

      本文标题:iOS开发网络篇—监测网络状态

      本文链接:https://www.haomeiwen.com/subject/zwvpsttx.html