iOS 检测网络状态

时间:2022-11-26 15:18:33

1.iOS平台是按照一直有网络连接的思路来设计的,开发者利用这一特点创造了很多优秀的第三方应用。大多数的iOS应用都需要联网,甚至有些应用严重依赖网络,没有网络就无法正常工作。

2.在你的应用尝试通过网络获取数据之前,你需要知道当前设备是否知道连接上了网络,甚至有时候你可能还需要知道当前网路是由wifi还是由移动蜂窝网络提供的。

3.“在网络访问失败的时候,应用没有做出适当的提示”是苹果的iOS审核团队拒绝一个应用的常见理由。苹果要求你必须先检测网络连接状态,当网络不可用的时候以某种方式告知用户,或者用其他优雅的方式进行处理。


Reachability类:

1.这个类用于检测当前网络状态,它不是SDK的一部分,可以在iOS Developer Library里找到这份代码。

从苹果网站上下载Reachability.zip文件,解压之。

2.重用Reachability类

    (1)把Reachability.h和Reachability.m文件拖到项目中。

    (2)添加框架:SystemConfiguration.framework。

3.同步的Reachability

    (1)使用同步的方式是比较简单,导入Reachability.h头文件,然后通过代码检查网络:

        #import “Reachability.h”

        。。。some code omitted…

       

Reachability *reach = [Reachability reachabilityForInternetConnection];

NetworkStatus status = [reach currentReachabilityStatus];


     (2)通过检查某个主机能否访问来判断当前网络是否可用:

       

Reachability *reach = [Reachability reachabilityWithHostName:@“www.apple.com”];

NetworkStatus status = [reach currentReachabilityStatus];


     (3)案例:

        创建一个工程,并添加Reachability.h和Reachability.m到工程中,并链接SystemConfiguration.framework.

        在AppDelegate.h头文件中导入Reachability.h,并添加一个实例方法。如下:

#import <UIKit/UIKit.h>
#import "Reachability.h"
@interface APLAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

-(NSString *)stringFromStatus:(NetworkStatus)status;
@end


  在AppDelegate.m中这样实现:如下:

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
Reachability *reach = [Reachability reachabilityForInternetConnection];
NetworkStatus status = [reach currentReachabilityStatus];

UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Reachability" message:[self stringFromStatus:status] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
return YES;

}


-(NSString *)stringFromStatus:(NetworkStatus)status{
NSString *string;
switch (status) {
case NotReachable:
string = @"NOT Reachable";
break;
case ReachableViaWiFi:
string = @"Reachable via WIFI";
break;
case ReachableViaWWAN:
string = @"Reachable via WWAN";
break;

default:
string = @"Unknown";
break;
}

return string;
}

4.异步的Reachability

    (1)异步的方式稍微复杂,不过通过这种方式可以来订阅实时的网络状态变化通知。导入Reachability.h头文件,然后注册一个对象来订阅网络状态变化的信息,网络状态变化的信息名称为kReachabilityChanged-Notification.如下:

   

[[NSNotificationCenter defaultCenter] addObserver:self

selector:@selector(reachabilityChanged:)

name:kReachabilityChangedNotification

object:nil];


    (2)你需要创建一个Reachability对象实例并开始向外发布网络状态变化的消息:

       

Reachability *reach = [[Reachability reachabilityWithHostName:@“www.apple.com”] retain];

[reach startNotifier];


    (3)当网络状态发生变化的时候,Reachability对象将调用reachabilityChanged:方法,可以在这个方法里面获取当前的网络状态,然后做相应的处理。

        - (void)reachabilityChanged:(NSNotification *)notification{

Reachability *reach = [notification object];

if([reach isKindOfClass:[Reachability class]]){

NetworkStatus status = [reach currentReachabilityStatus];

//Insert your code here

}

}


 

5.原生 Reachability API

前面将的Reachability类实际上是苹果公司对SCNetworkReachability API的封装,这个API定义在SystemConfigure.framework库中。如果有其他特别的需求,也可以直接使用这个原生的SCNetworkReachability类。

6.可以为Reachability增加2G/3G/4G的判断

Reachability.h里增加三种状态

typedef enum : NSInteger {
NotReachable = 0,
ReachableViaWiFi,
ReachableViaWWAN,
ReachableVia2G,
ReachableVia3G,
ReachableVia4G
} NetworkStatus;
Reachability.m里导入#import <CoreTelephony/CTTelephonyNetworkInfo.h>

替换这个方法

- (NetworkStatus)networkStatusForFlags:(SCNetworkReachabilityFlags)flags
{
PrintReachabilityFlags(flags, "networkStatusForFlags");
if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
{
// The target host is not reachable.
return NotReachable;
}

NetworkStatus returnValue = NotReachable;

if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
{
/*
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 ) != 0) ||
(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
{
/*
... and the connection is on-demand (or on-traffic) if the calling application is using the CFSocketStream or higher APIs...
*/

if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
{
/*
... 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.
*/
/*! 版本兼容
*/
float systemVersion = [UIDevice currentDevice].systemVersion.floatValue;
if (systemVersion>=7.0) {
CTTelephonyNetworkInfo * telephonyNetwork = [CTTelephonyNetworkInfo new];
/*! 获取当前网络的名字
*/
NSString * NetworkNameString = [telephonyNetwork currentRadioAccessTechnology];
if (NetworkNameString) {
/*! 网络区分
CTRadioAccessTechnologyGPRS - 2G
CTRadioAccessTechnologyEdge - 2G (sometimes called 2.5G)
CTRadioAccessTechnologyWCDMA - 3G
CTRadioAccessTechnologyHSDPA - 3G (sometimes called 3.5G)
CTRadioAccessTechnologyHSUPA - 3G
CTRadioAccessTechnologyCDMA1x - 2G
CTRadioAccessTechnologyCDMAEVDORev0 - 3G
CTRadioAccessTechnologyCDMAEVDORevA - 3G
CTRadioAccessTechnologyCDMAEVDORevB - 3G
CTRadioAccessTechnologyeHRPD - 3G (or 3.5 - eHRPD is to allow migration from CDMA EVDO to LTE)
CTRadioAccessTechnologyLTE - 4G (allowed to be called 4G by the ITU as mentioend above)
*/
if ([NetworkNameString isEqualToString:CTRadioAccessTechnologyGPRS]||[NetworkNameString isEqualToString:CTRadioAccessTechnologyEdge]||[NetworkNameString isEqualToString:CTRadioAccessTechnologyCDMA1x]) {
returnValue = ReachableVia2G;
}else if ([NetworkNameString isEqualToString:CTRadioAccessTechnologyWCDMA]||[NetworkNameString isEqualToString:CTRadioAccessTechnologyHSDPA]||[NetworkNameString isEqualToString:CTRadioAccessTechnologyHSUPA]||[NetworkNameString isEqualToString:CTRadioAccessTechnologyHSUPA]||[NetworkNameString isEqualToString:CTRadioAccessTechnologyCDMAEVDORev0]||[NetworkNameString isEqualToString:CTRadioAccessTechnologyCDMAEVDORevA]||[NetworkNameString isEqualToString:CTRadioAccessTechnologyCDMAEVDORevB]||[NetworkNameString isEqualToString:CTRadioAccessTechnologyeHRPD]){
returnValue = ReachableVia3G;
}else if ([NetworkNameString isEqualToString:CTRadioAccessTechnologyLTE]){
returnValue = ReachableVia4G;
}else{
returnValue = ReachableViaWWAN;
}
}else{
returnValue = ReachableViaWWAN;
}
}else{
/*! 低版本
*/
returnValue = ReachableViaWWAN;
}
}
return returnValue;
}


参考:

http://www.bkjia.com/IOSjc/962868.html

http://blog.csdn.net/zhoushuangjian511/article/details/56013002