iOS检测联网
来源:互联网 发布:网络十大小说排行榜 编辑:程序博客网 时间:2024/05/29 09:49
在ios移动开发过程中,只要不是单机的移动的开发,基本都有链接网络的操作。这次主要讲的是用Reachability来判断iphone是否处于联网状态中。
首先,苹果官网提供了Reachability的接口。
https://developer.apple.com/library/ios/samplecode/Reachability/Introduction/Intro.html
在这里,可以下载Reachability.m和Reachability.h,然后将这两个文件导入到自己的项目里面。
官网给出的主要是三种状态:
网络不可用:NoteReachable
使用的是本地运营商网络:ReachableViaWiFi
使用的Wi-Fi网络:ReachableViaWWAN
接口代码如下:
typedef enum : NSInteger { NotReachable = 0, ReachableViaWiFi, ReachableViaWWAN} NetworkStatus;
然后,就需要在自己的代码里面调用相应的接口。
在官网给定的接口中,可以判断出来是WI-FI连接还是本地运营商链接。代码如下:
- (void)testConnection { BOOL result = YES; Reachability *reach=[Reachability sharedReachability]; [reach setHostName:@“www.baidu.com”]; NetworkStatus status; status=[reach remoteHostStatus]; //本地运营商 { [AlertView showNotice:@"使用本地网络"]; } //WI-FI连接 else if (status == ReachableViaWiFiNetwork) { [AlertView showNotice:@"使用WIFI网络"]; }}
如果仅仅是判断iphone是否处于联网状态中,那就需要改动一下Reachability.m和Reachability.h这两个文件,在里面添加一些判定的代码。
Reachability.h
typedef void (^NetworkReachable)(Reachability * reachability);typedef void (^NetworkUnreachable)(Reachability * reachability);@interface Reachability : NSObject@property (nonatomic, copy) NetworkReachable reachableBlock;@property (nonatomic, copy) NetworkUnreachable unreachableBlock;
Reachability.m
#if NEEDS_DISPATCH_RETAIN_RELEASE@property (nonatomic, assign) dispatch_queue_t reachabilitySerialQueue;#else@property (nonatomic, strong) dispatch_queue_t reachabilitySerialQueue;#endif
在需要检测网络连接的相应View Controller中加入如下代码:
Reachability *reach = [Reachability reachabilityWithHostname:@"www.baidu.com"];reach.reachableBlock = ^(Reachability *reach){ dispatch_async(dispatch_get_main_queue(), ^{ [reach stopNotifier]; //提示网络可达 [AlertView showNotice:@"网络正常"]; }); }; reach.unreachableBlock = ^(Reachability*reach) { dispatch_async(dispatch_get_main_queue(), ^{ [reach stopNotifier]; //提示网络不可达 [AlertView showNotice:@"您处于离线模式(网络缺失)"]; }); }; // start the notifier which will cause the reachability object to retain itself! [reach startNotifier];
最后运行出来的效果图:
0 0
- iOS检测联网
- 【iOS开发】检测联网状态 - Reachability
- 检测计算机是否联网
- 检测当前是否联网
- JS 检测是否联网
- Delphi 快速检测是否联网
- iOS判断是否联网
- iOS - Xcode联网设置
- MFC下检测计算机是否联网
- wifi 、3G网络联网状态检测
- Windows中检测联网(一)
- Windows中检测联网(二)
- Windows中检测联网(三)
- xamarin.forms 联网状态检测,Connectivity Plugin
- Reachability框架(联网状态的检测)
- C#检测本机是否联网
- js 检测浏览器是否联网 (navigator.onLine)
- 联网检测身份证验证返照片
- 截图保存格式问题-最好保存为png格式
- HDOJ 2013 蟠桃记
- 医疗大数据预处理
- Nginx服务器配置404页面
- HDOJ 2014 青年歌手大奖赛_评委会打分
- iOS检测联网
- 为mysql数据库建立索引
- HDOJ 2015 偶数求和
- 南大软院大神养成计划--js
- 最近解决tab滑动及点击快速切换,快速点击压力测试系统会崩溃问题心得
- HDOJ 2016 数据的交换输出
- 创建多线程的第一种方法
- Nginx配置服务器SSI
- 机器学习和计算机视觉有关的数学