iOS-网络检测的几种方法

1.AFN框架中的:AFNetworkReachabilityManager

//AFN判断网络

-(void)getInternetStatue{

// 1.获得网络监控的管理者

AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManagersharedManager];

// 2.设置网络状态改变后的处理

[mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatusstatus) {

// 当网络状态改变了,就会调用这个block

switch (status) {

caseAFNetworkReachabilityStatusUnknown://未知网络

NSLog(@"未知网络");

break;

caseAFNetworkReachabilityStatusNotReachable://没有网络(断网)

NSLog(@"没有网络(断网)");

break;

caseAFNetworkReachabilityStatusReachableViaWWAN://手机自带网络

NSLog(@"手机自带网络");

break;

caseAFNetworkReachabilityStatusReachableViaWiFi:// WIFI

NSLog(@"WIFI");

break;

}

if(status ==AFNetworkReachabilityStatusReachableViaWWAN || status ==AFNetworkReachabilityStatusReachableViaWiFi)

{

[email protected]"有网络";

NSLog(@"有网");

}else

{

[email protected]"没网络";

    NSLog(@"没有网");

UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:@"网络失去连接"message:nildelegate:selfcancelButtonTitle:@"取消"otherButtonTitles:nil,nil];

alert.delegate =self;

[alert show];

}

}];

// 3.开始监控

[mgr startMonitoring];

}

========= 2.苹果自带reachability =========

1、代表网络状态的枚举:

typedef enum : NSInteger {
    NotReachable = 0, //无网络可用
    ReachableViaWiFi, //WiFi连接
    ReachableViaWWAN //无限广域网连接
} NetworkStatus;2、下面是相关接口和注释
/*!
 * 用于检测网络请求是否可以到达指定的主机名
 */
+ (instancetype)reachabilityWithHostName:(NSString *)hostName;

/*!
 * 用于检测网络请求是否可以到达给定的ip地址
 */
+ (instancetype)reachabilityWithAddress:(const struct sockaddr_in *)hostAddress;

/*!
 * 检查默认的路由器是否有效. 用于不连接到特定主机的应用.
 */
+ (instancetype)reachabilityForInternetConnection;

/*!
 * 检测本地的WiFi连接是否有效
 */
+ (instancetype)reachabilityForLocalWiFi;

/*!
 * 开始监听在当前的runloop中的通知.
 */
- (BOOL)startNotifier;
- (void)stopNotifier;

//获取网络状态
- (NetworkStatus)currentReachabilityStatus;

/*!
 * 连接需求
 */
- (BOOL)connectionRequired;
3、网络连接状态改变时的通知标识
NSString *kReachabilityChangedNotification = @"kNetworkReachabilityChangedNotification";
//需要把该工程中的Reachability.h 和 Reachability.m 拷贝到你的工程中,同时需要把SystemConfiguration.framework 添加到工程中,

//创建Reachability

Reachability *reach = [Reachability reachabilityForInternetConnection];

reach = [Reachability reachabilityWithHostName:@"www.baidu.com"] ;

// 开始监控网络(一旦网络状态发生改变, 就会发出通知kReachabilityChangedNotification)

[reach startNotifier];

//开启通知---方式一:

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

//// 处理网络状态改变

- (void)networkStateChange:(NSNotification *)note{

Reachability * reach = [noti object];

NetworkStatus status = [reach currentReachabilityStatus];

// 3.判断网络状态

if (status== NotReachable) {

NSLog(@"没网");

} else if (status==ReachableViaWWAN) {

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

} else if(status==ReachableViaWiFi){

NSLog(@"通过wifi");

}}

注册通知----方式二:

[[NSNotificationCenter defaultCenter] addObserver:self

selector:@selector(reachabilityChanged:)

name:kReachabilityChangedNotification

object:nil];//网络状态监控

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

Reachability * reach = [noti object];

if([reach isReachable]) {

[self setMBProgressWithNumTip:@"网络已连接"];

NSLog(@"网络已经连接");

[LYCommanManager sharedManager].isreachable=[reachisReachable];

[[NSNotificationCenterdefaultCenter]postNotificationName:@"startloading" object:nil];//发送通知开始加载网页

} else {

NSLog(@"网络未连接");

[self setMBProgressWithNumTip:@"网络未连接"];

[LYCommanManager sharedManager].isreachable=[reachisReachable];

[[NSNotificationCenterdefaultCenter]postNotificationName:@"endloading" object:nil];//发送通知结束加载

}

}

-(void)viewdidoad{

if([LYCommanManager sharedManager].isreachable){

[self setMBProgressWithNum:@"loading..."];

NSLog(@"当前是有网de");

}else {

[self setMBProgressWithNumTip:@"无网络连接"];

NSLog(@"当前没有网络");

}

[[NSNotificationCenter defaultCenter]addObserver:selfselector:@selector(finishLoading) name:@"endloading" object:nil];

[[NSNotificationCenter defaultCenter]addObserver:selfselector:@selector(startLoading) name:@"startloading"object:nil];

}

//联网后重新加载网页

-(void)startLoading{

[self setTrainTicketWithMKweb];

}

//结束加载提示

-(void)finishLoading{

[MBProgressHUD hideHUDForView:self.view animated:YES];

}

=========3.通过状态栏判断网络=========

//从状态栏中获取网络类型,代码如下:

-(NSString *)getNetWorkStates{

UIApplication *app = [UIApplicationsharedApplication];

NSArray *children = [[[appvalueForKeyPath:@"statusBar"]valueForKeyPath:@"foregroundView"]subviews];

NSLog(@"---%@---",children);

NSString *state = [[NSStringalloc]init];

NSLog(@"--空字符串0-%@",state);

int netType =0;

//获取到网络返回码

for (id childin children) {

if([childisKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]) {

//获取到状态栏

netType = [[child valueForKeyPath:@"dataNetworkType"]intValue];

NSLog(@"netType---%d",netType);

switch (netType) {

case 0:

state = @"无网络";

//无网模式

break;

case 1:

state = @"2G";

break;

case 2:

state = @"3G";

break;

case 3:

state = @"4G";

break;

case 5:

{

state = @"wifi";

NSLog(@"5");

break;

default:

break;

}

}

}

//根据状态选择

}

return state;

}

时间: 2024-08-03 13:06:11

iOS-网络检测的几种方法的相关文章

网络超时检测的三种方法

作者:于老师,华清远见嵌入式学院讲师. 网络通信中,很多操作会使得进程阻塞,这时我们要设定时间,到时间后强制返回,避免进程在没有数据的情况下无限阻塞 这里我们总结一下网络超时检测的三种方法: 通过setsockopt设置套接字属性SO_RCVTIMEO struct timeval t = {5, 0}           if  (setsockopt(listenfd, SOL_SOCKET, SO_RCVTIMEO, &t, sizeof(t)) == -1) {             

iOS 播放音频的几种方法

iOS 播放音频的几种方法 iPhone OS 主要提供以下了几种播放音频的方法: System Sound Services AVAudioPlayer 类 Audio Queue Services OpenAL 1. System Sound Services System Sound Services 是最底层也是最简单的声音播放服务,调用 AudioServicesPlaySystemSound 这个方法就可以播放一些简单的音频文件,使用此方法只适合播放一些很小的提示或者警告音,因为它有

关闭ios虚拟键盘的几种方法

在iOS应用开发中,有三类视图对象会打开虚拟键盘,进行输入操作,但如何关闭虚拟键盘,却没有提供自动化的方法.这个需要我们自己去实现.这三类视图对象分别是UITextField,UITextView和UISearchBar. 这里介绍一下UITextField中关闭虚拟键盘的几种方法. 第一种方法,使用它的委托UITextFieldDelegate中的方法textFieldShouldReturn:来关闭虚拟键盘. 在UITextField视图对象如birdNameInput所在的类中实现这个方法

iOS清理缓存的几种方法

iOS清理缓存的几种方法,有需要的朋友可以参考下: 1.计算文件大小: - (long long) fileSizeAtPath:(NSString*) filePath{ NSFileManager* manager = [NSFileManager defaultManager]; if ([manager fileExistsAtPath:filePath]){ return [[manager attributesOfItemAtPath:filePath error:nil] file

打开网络适配的两种方法

打开网络适配有两种方法 第一种是在Info.plist文件里添加XML代码 具体步骤:右击Info.plist文件 选择Open As里面的Source Code 然后在文件底部插入下面代码 [html] view plain copy <key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict> 第二种

iOS拨打电话(三种方法)

iOS拨打电话(三种方法) 查了很多地方的关于iOS程序拨打电话,大都不全,今天我总结了三种方法,各有不同,拿来给大家分享,希望给大家有所帮助 1,这种方法,拨打完电话回不到原来的应用,会停留在通讯录里,而且是直接拨打,不弹出提示NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",@"186xxxx6979"];    //            NSLog(@"s

iOS获取网络类型的四种方法

Reachability类只能区分WIFI和WWAN类型,却无法区分2G网和3G网. 网上也有些方法,却都存在Bug. 经过网上查找资料和测试,基本上总结了以下几种方法: 1.使用导航栏的方式:(私有API) 代码: typedef enum { NetWorkType_None = 0, NetWorkType_WIFI, NetWorkType_2G, NetWorkType_3G, } NetWorkType; UIApplication *application = [UIApplica

iOS 批量上传图片的 3 种方法

AFNetworking 在去年年底升级到了 3.0.这个版本更新想必有很多好处,然而让我吃惊的是,它并没有 batch request 接口.之前的 1.x 版本.2.x 版本都实现了这个很常见的需求,不知道作者为何选择在 3.x 中去掉它. 在 AFNetworking 2 中,我们只需一行代码就能解决批量上传的问题: [AFURLConnectionOperation batchOfRequestOperations:operations progressBlock:^(NSUIntege

分析iOS Crash文件:符号化iOS Crash文件的3种方法

转自:http://www.cocoachina.com/industry/20140514/8418.html 转自wufawei的博客 当你的应用提交到App Store或者各个渠道之后,请问你多久会拿到crash文件?你如何分析crash文件的呢? 上传crash文件 你的应用应当有模块能够在应用程序crash的时候上传crash信息. 要么通过用户反馈拿到crash文件,要么借助自己或第3方的crash上传模块拿到crash文件. 今天要分析的场景是你拿到用户的.crash文件之后,如何

隐藏ios虚拟键盘的几种方法

在iOS应用开发中,有三类视图对象会打开虚拟键盘,进行输入操作,但如何关闭虚拟键盘,却没有提供自动化的方法.这个需要我们自己去实现.这三类视图对象分别是UITextField,UITextView和UISearchBar. 这里介绍一下UITextField中关闭虚拟键盘的几种方法. (miki西游 @mikixiyou 原文链接: http://mikixiyou.iteye.com/blog/1753330 ) 第一种方法,使用它的委托UITextFieldDelegate中的方法textF