使用 Reachability 获取网络状态

Reachability
source https://developer.apple.com/library/ios/samplecode/Reachability/Introduction/Intro.html
reachability 为苹果官方demo提供的一个检测网络状态的代码,下载源码后本人对其进行了修改,修改后源码:
reachability.h + reachability.m
#import <Foundation/Foundation.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <netinet/in.h> typedef enum : NSInteger {
NotReachable = ,
ReachableViaWiFi,
ReachableViaWWAN
} NetworkStatus; extern NSString *kReachabilityChangedNotification; @interface Reachability : NSObject /*!
* Use to check the reachability of a given host name.
*/
+ (instancetype)reachabilityWithHostName:(NSString *)hostName; /*!
* Use to check the reachability of a given IP address.
*/
+ (instancetype)reachabilityWithAddress:(const struct sockaddr_in *)hostAddress; /*!
* Checks whether the default route is available. Should be used by applications that do not connect to a particular host.
*/
+ (instancetype)reachabilityForInternetConnection; /*!
* Checks whether a local WiFi connection is available.
*/
+ (instancetype)reachabilityForLocalWiFi; /*!
* Start listening for reachability notifications on the current run loop.
*/
- (BOOL)startNotifier;
- (void)stopNotifier; - (NetworkStatus)currentReachabilityStatus; /*!
* WWAN may be available, but not active until a connection has been established. WiFi may require a connection for VPN on Demand.
*/
- (BOOL)connectionRequired; /*!
* 测试是否能连接网
*/
+ (NetworkStatus)isExistNetwork; @end
#import <arpa/inet.h>
#import <ifaddrs.h>
#import <netdb.h>
#import <sys/socket.h> #import <CoreFoundation/CoreFoundation.h> #import "Reachability.h" NSString *kReachabilityChangedNotification = @"kNetworkReachabilityChangedNotification"; #pragma mark - Supporting functions #define kShouldPrintReachabilityFlags 1 static void PrintReachabilityFlags(SCNetworkReachabilityFlags flags, const char* comment)
{
#if kShouldPrintReachabilityFlags NSLog(@"Reachability Flag Status: %c%c %c%c%c%c%c%c%c %s\n",
(flags & kSCNetworkReachabilityFlagsIsWWAN) ? 'W' : '-',
(flags & kSCNetworkReachabilityFlagsReachable) ? 'R' : '-', (flags & kSCNetworkReachabilityFlagsTransientConnection) ? 't' : '-',
(flags & kSCNetworkReachabilityFlagsConnectionRequired) ? 'c' : '-',
(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) ? 'C' : '-',
(flags & kSCNetworkReachabilityFlagsInterventionRequired) ? 'i' : '-',
(flags & kSCNetworkReachabilityFlagsConnectionOnDemand) ? 'D' : '-',
(flags & kSCNetworkReachabilityFlagsIsLocalAddress) ? 'l' : '-',
(flags & kSCNetworkReachabilityFlagsIsDirect) ? 'd' : '-',
comment
);
#endif
} static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info)
{
#pragma unused (target, flags)
NSCAssert(info != NULL, @"info was NULL in ReachabilityCallback");
NSCAssert([(__bridge NSObject*) info isKindOfClass: [Reachability class]], @"info was wrong class in ReachabilityCallback"); Reachability* noteObject = (__bridge Reachability *)info;
// Post a notification to notify the client that the network reachability changed.
[[NSNotificationCenter defaultCenter] postNotificationName: kReachabilityChangedNotification object: noteObject];
} #pragma mark - Reachability implementation @implementation Reachability
{
BOOL _alwaysReturnLocalWiFiStatus; //default is NO
SCNetworkReachabilityRef _reachabilityRef;
} + (instancetype)reachabilityWithHostName:(NSString *)hostName
{
Reachability* returnValue = NULL;
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, [hostName UTF8String]);
if (reachability != NULL)
{
returnValue= [[self alloc] init];
if (returnValue != NULL)
{
returnValue->_reachabilityRef = reachability;
returnValue->_alwaysReturnLocalWiFiStatus = NO;
}
}
return returnValue;
} + (instancetype)reachabilityWithAddress:(const struct sockaddr_in *)hostAddress
{
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)hostAddress); Reachability* returnValue = NULL; if (reachability != NULL)
{
returnValue = [[self alloc] init];
if (returnValue != NULL)
{
returnValue->_reachabilityRef = reachability;
returnValue->_alwaysReturnLocalWiFiStatus = NO;
}
}
return returnValue;
} + (instancetype)reachabilityForInternetConnection
{
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET; return [self reachabilityWithAddress:&zeroAddress];
} + (instancetype)reachabilityForLocalWiFi
{
struct sockaddr_in localWifiAddress;
bzero(&localWifiAddress, sizeof(localWifiAddress));
localWifiAddress.sin_len = sizeof(localWifiAddress);
localWifiAddress.sin_family = AF_INET; // IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0.
localWifiAddress.sin_addr.s_addr = htonl(IN_LINKLOCALNETNUM); Reachability* returnValue = [self reachabilityWithAddress: &localWifiAddress];
if (returnValue != NULL)
{
returnValue->_alwaysReturnLocalWiFiStatus = YES;
} return returnValue;
} #pragma mark - Start and stop notifier - (BOOL)startNotifier
{
BOOL returnValue = NO;
SCNetworkReachabilityContext context = {, (__bridge void *)(self), NULL, NULL, NULL}; if (SCNetworkReachabilitySetCallback(_reachabilityRef, ReachabilityCallback, &context))
{
if (SCNetworkReachabilityScheduleWithRunLoop(_reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode))
{
returnValue = YES;
}
} return returnValue;
} - (void)stopNotifier
{
if (_reachabilityRef != NULL)
{
SCNetworkReachabilityUnscheduleFromRunLoop(_reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
}
} - (void)dealloc
{
[self stopNotifier];
if (_reachabilityRef != NULL)
{
CFRelease(_reachabilityRef);
}
} #pragma mark - Network Flag Handling - (NetworkStatus)localWiFiStatusForFlags:(SCNetworkReachabilityFlags)flags
{
PrintReachabilityFlags(flags, "localWiFiStatusForFlags");
NetworkStatus returnValue = NotReachable; if ((flags & kSCNetworkReachabilityFlagsReachable) && (flags & kSCNetworkReachabilityFlagsIsDirect))
{
returnValue = ReachableViaWiFi;
} return returnValue;
} - (NetworkStatus)networkStatusForFlags:(SCNetworkReachabilityFlags)flags
{
PrintReachabilityFlags(flags, "networkStatusForFlags");
if ((flags & kSCNetworkReachabilityFlagsReachable) == )
{
// The target host is not reachable.
return NotReachable;
} NetworkStatus returnValue = NotReachable; if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == )
{
/*
If the target host is reachable and no connection is required then we'll assume (for now) that you're on Wi-Fi...
*/
returnValue = ReachableViaWiFi;
} if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != ) ||
(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != ))
{
/*
... and the connection is on-demand (or on-traffic) if the calling application is using the CFSocketStream or higher APIs...
*/ if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == )
{
/*
... and no [user] intervention is needed...
*/
returnValue = ReachableViaWiFi;
}
} if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
{
/*
... but WWAN connections are OK if the calling application is using the CFNetwork APIs.
*/
returnValue = ReachableViaWWAN;
} return returnValue;
} - (BOOL)connectionRequired
{
NSAssert(_reachabilityRef != NULL, @"connectionRequired called with NULL reachabilityRef");
SCNetworkReachabilityFlags flags; if (SCNetworkReachabilityGetFlags(_reachabilityRef, &flags))
{
return (flags & kSCNetworkReachabilityFlagsConnectionRequired);
} return NO;
} - (NetworkStatus)currentReachabilityStatus
{
NSAssert(_reachabilityRef != NULL, @"currentNetworkStatus called with NULL SCNetworkReachabilityRef");
NetworkStatus returnValue = NotReachable;
SCNetworkReachabilityFlags flags; if (SCNetworkReachabilityGetFlags(_reachabilityRef, &flags))
{
if (_alwaysReturnLocalWiFiStatus)
{
returnValue = [self localWiFiStatusForFlags:flags];
}
else
{
returnValue = [self networkStatusForFlags:flags];
}
} return returnValue;
} + (NetworkStatus)isExistNetwork
{
NetworkStatus isExistenceNetwork; //单例
static Reachability *reachability = nil; //服务器地址选择了百度
if (reachability == nil)
{
reachability = [Reachability reachabilityWithHostName:@"www.baidu.com"];
} switch([reachability currentReachabilityStatus]) {
case NotReachable:
isExistenceNetwork = NotReachable;
break;
case ReachableViaWWAN:
isExistenceNetwork = ReachableViaWWAN;
break;
case ReachableViaWiFi:
isExistenceNetwork = ReachableViaWiFi;
break;
} return isExistenceNetwork;
} @end
直接使用下面的代码来得到网络信息,是单例模式,无需担心浪费内存
[Reachability isExistNetwork];
其返回3个枚举值,判断一下即可,
NotReachable, ReachableViaWiFi, ReachableViaWWAN
使用通知来监听网络状态
1.定义属性(strong)
@property (nonatomic, strong) Reachability *hostReachability;
@property (nonatomic, strong) Reachability *internetReachability;
@property (nonatomic, strong) Reachability *wifiReachability;
2.指定监听的方法
- (void) reachabilityChanged:(NSNotification *)note
{
Reachability *tmp = [note object];
NSLog(@"%d", [tmp currentReachabilityStatus]);
}
3.初始化以及监听
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object:nil];
NSString *remoteHostName = @"www.baidu.com";
_hostReachability = [Reachability reachabilityWithHostName:remoteHostName];
[_hostReachability startNotifier];
_internetReachability = [Reachability reachabilityForInternetConnection];
[_internetReachability startNotifier];
_wifiReachability = [Reachability reachabilityForLocalWiFi];
[_wifiReachability startNotifier];
使用 Reachability 获取网络状态的更多相关文章
- iOS 获取网络状态
在iOS开发者,获取网络状态比较常用 -(NSString *)getNetWorkStates{ UIApplication *app = [UIApplication sharedApplicat ...
- android开发获取网络状态,wifi,wap,2g,3g.工具类(一)
android开发获取网络状态整理: package com.gzcivil.utils; import android.content.Context; import android.net.Con ...
- Android获取网络状态
Android获取网络状态 学习自 https://developer.android.google.cn/reference/android/net/ConnectivityManager http ...
- 微信小程序 --- 获取网络状态
获取网络状态:wx.getNetworkType btnclick:function(){ wx.getNetworkType({ success:function(res){ console.log ...
- React Native之Fetch简单封装、获取网络状态
1.Fetch的使用 fetch的使用非常简单,只需传入请求的url fetch('https://facebook.github.io/react-native/movies.json'); 当然是 ...
- C#获取网络状态
/// <summary> /// 获取网络状态 /// </summary> /// <param name="ip">目标IP地址</ ...
- [React Native]获取网络状态
使用React Native,可以使用NetInfo API获取手机当前的各个网络状态. componentWillMount() { NetInfo.fetch().done((status)=&g ...
- iOS开发网络篇—Reachability检测网络状态
前言:当应用程序需要访问网络的时候,它首先应该检查设备的网络状态,确认设备的网络环境及连接情况,并针对这些情况提醒用户做出相应的处理.最好能监听设备的网络状态的改变,当设备网络状态连接.断开时,程序也 ...
- iOS网络4——Reachability检测网络状态
一.整体介绍 前面已经介绍了网络访问的NSURLSession.NSURLConnection,还有网页加载有关的webview,基本满足通常的网络相关的开发. 其实在网络开发中还有比较常用的就是网络 ...
随机推荐
- CCF CSP 201409-2 画图
CCF计算机职业资格认证考试题解系列文章为meelo原创,请务必以链接形式注明本文地址 CCF CSP 201409-2 画图 问题描述 在一个定义了直角坐标系的纸上,画一个(x1,y1)到(x2,y ...
- day1作业:登录接口
作业一:编写登陆接口 1.输入用户名和密码 2.认证成功后显示欢迎信息 3.输错三次后锁定 思路: (1)用户输入用户名: (2)去锁定文件中验证用户名是否锁定: (3)去当前用户验证用户是否存在: ...
- python 创建项目
项目骨架 nose 测试框架 Windows 10 配置 创建骨架项目目录 Windows 10 的 PowerShell mkdir projects cd projects/ mkdir skel ...
- CSS 显示或隐藏子元素
很多时候我们仅仅只是想让鼠标移动入某个元素,然后显示出某个元素. 大多数博客的标题或内容都是:使用CSS实现鼠标悬停在一行上,显示某些元素 很遗憾,这是错误的,鼠标悬停后,尽管CSS标准中有定义此种方 ...
- java中int和Integer比较
java中int和Integer比较 一,类型区别 我们知道java中由两种数据类型,即基本类型和对象类型,int就是基本数据类型,而Integer是一个class,也习惯把Integer叫做int的 ...
- GPL、BSD和Apache开源许可证
参考资料 五种开源协议的比较(BSD,Apache,GPL,LGPL,MIT) 如何选择开源许可证? - 阮一峰的网络日志 开源许可证教程 - 阮一峰的网络日志 简介 自由软件许可证由FSF(Free ...
- Python 随机数函数
random.random random.random()用于生成一个0到1的随机符点数: 0 <= n < 1.0 描述 random() 方法返回随机生成的一个实数,它在[0,1)范围 ...
- 【转】高效率编辑器VIM
最近实习的时候需要在服务器上做Debug,不得不用到vim的相关操作.以前对vim这种被码农无数赞扬的神器望而却步,但今天试了之后感觉还是不错的.以后争取少用鼠标,少用insert模式. 这是从网上看 ...
- MySQL 语句分析
公司使用的数据库是 MySQL 数据库,我对于 MySQL 的了解仅仅是上学的时候学过PHP略微了解. 我认为,作为一个后端程序员,除了在意功能能不能实现之外, 在实现功能之后,还要去想有没有更好的办 ...
- Linux下禅道系统的搭建
说明: 禅道系统的搭建,分两大部分 1.xampp环境的搭建 2.禅道系统的搭建 *********************************************************** ...