iOS检测网络状态
来源:互联网 发布:map源码 编辑:程序博客网 时间:2024/05/20 04:28
很多工程多需要用到网络,时刻需要对网络链接进行判断,下面介绍怎么使用网络链接第三方,进行判断网络以及判断是wifi,4G网络等等;
少说废话上代码:
#import "ViewController.h"#import "Reachability.h"@interface ViewController ()@property (nonatomic,strong) Reachability *netConnect;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; /*************** 方法1 : block块 ***************/ /* *1.最好是本公司的网站; *2.国内能够访问的网站; */ NSString *urlStr = @"写一个能连接的网址"; //创建监听络的对象self.netConnect self.netConnect = [Reachability reachabilityWithHostname:urlStr]; __weak typeof(self) weakSelf = self; //网络连接成功 self.netConnect.reachableBlock = ^(Reachability * reachability) { //打印网络名称,是 2G 网络还是 wifi ; NSLog(@"connect success :newName = %@",weakSelf.netConnect.currentReachabilityString); //主线程 dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"reload data"); }); }; //网络连接失败 self.netConnect.unreachableBlock = ^(Reachability * reachability) { NSLog(@"connect error"); //主线程 dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"to do something"); }); }; //不要忘记启动噢 [self.netConnect startNotifier]; /*************** 方法2 : 通知 ***************/ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:self.netConnect]; }- (void)reachabilityChanged:(NSNotification *)notification{ /* *currentReachabilityStatus * * NotReachable = 0, * ReachableViaWiFi = 2, * ReachableViaWWAN = 1 */ Reachability *reach = notification.object; switch (reach.currentReachabilityStatus) { case NotReachable: NSLog(@"connect error"); break; case ReachableViaWiFi: NSLog(@"connect wifi"); break; case ReachableViaWWAN: NSLog(@"connect wwan"); break; default: break; }}
如果转载请注明转于:AirZilong的博客
3 0
- iOS---检测网络状态
- ios 检测网络状态
- 检测iOS网络状态
- iOS检测网络状态
- iOS检测网络状态
- iOS 检测网络状态
- IOS检测网络连接状态
- IOS检测网络连接状态
- IOS检测网络连接状态
- IOS检测网络连接状态
- IOS检测网络连接状态
- IOS检测网络连接状态
- IOS检测网络连接状态
- IOS检测网络连接状态
- ios检测网络状态Reachability
- iOS检测网络连接状态
- iOS 实时检测网络状态
- iOS开发-检测网络状态
- 分享一个仿就看天气应用源码
- Java Collection List Set Map 的区别
- mysql显示中文乱码
- IE8的select
- Eclipse问题 A cycle was detected in the build path of project: XXX
- iOS检测网络状态
- JSON与XML的区别比较
- css控制div高度自适应
- 美团在Redis上踩过的一些坑-2.bgrewriteaof问题
- Go语言核心之美 1.3-赋值及类型声明篇
- GSM模块通过国家网络授时中心获取网络时间同步
- 美团在Redis上踩过的一些坑-3.redis内存占用飙升
- 【转】MySQL编码问题
- 学习scala的点点滴滴(2)-与java交互