[iOS 多线程 & 网络 - 2.8] - 检测网络状态
(1)让用户了解自己的网络状态,防止一些误会(比如怪应用无能)
(2)根据用户的网络状态进行智能处理,节省用户流量,提高用户体验
WIFI\3G网络:自动下载高清图片
低速网络:只下载缩略图
https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip
1 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 2 // 检测wifi状态 3 Reachability *wifiStatus = [Reachability reachabilityForLocalWiFi]; 4 5 // 检测手机网络状态 6 Reachability *netStatus = [Reachability reachabilityForInternetConnection]; 7 8 // 判断网络状态 9 if ([wifiStatus currentReachabilityStatus] != NotReachable) { 10 NSLog(@"正在使用wifi上网"); 11 } else if ([netStatus currentReachabilityStatus] != NotReachable) { 12 NSLog(@"正在使用手机网络上网"); 13 } else { 14 NSLog(@"没有网络"); 15 } 16 } 17
1 // 2 // ViewController.m 3 // ReachabilityDemo 4 // 5 // Created by hellovoidworld on 15/1/28. 6 // Copyright (c) 2015年 hellovoidworld. All rights reserved. 7 // 8 9 #import "ViewController.h" 10 #import "Reachability.h" 11 12 @interface ViewController () 13 14 @property(nonatomic, strong) Reachability *networkStatus; 15 16 @end 17 18 @implementation ViewController 19 20 - (void)viewDidLoad { 21 [super viewDidLoad]; 22 // Do any additional setup after loading the view, typically from a nib. 23 24 // 实时监控手机联网状态 25 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(detectNetworkStatus) name:kReachabilityChangedNotification object:nil]; 26 27 // 开启通知发送 28 self.networkStatus = [Reachability reachabilityForInternetConnection]; 29 [self.networkStatus startNotifier]; 30 } 31 32 - (void)dealloc { 33 // 停止发送通知 34 [self.networkStatus stopNotifier]; 35 36 // 切记要删除通知 37 [[NSNotificationCenter defaultCenter] removeObserver:self]; 38 } 39 40 // 用WIFI 41 // [wifi currentReachabilityStatus] != NotReachable 42 // [conn currentReachabilityStatus] != NotReachable 43 44 // 没有用WIFI, 只用了手机网络 45 // [wifi currentReachabilityStatus] == NotReachable 46 // [conn currentReachabilityStatus] != NotReachable 47 48 // 没有网络 49 // [wifi currentReachabilityStatus] == NotReachable 50 // [conn currentReachabilityStatus] == NotReachable 51 52 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 53 [self detectNetworkStatus]; 54 } 55 56 - (void) detectNetworkStatus { 57 // 检测wifi状态 58 Reachability *wifiStatus = [Reachability reachabilityForLocalWiFi]; 59 60 // 检测手机网络状态 61 Reachability *netStatus = [Reachability reachabilityForInternetConnection]; 62 63 // 判断网络状态 64 if ([wifiStatus currentReachabilityStatus] != NotReachable) { 65 NSLog(@"正在使用wifi上网"); 66 } else if ([netStatus currentReachabilityStatus] != NotReachable) { 67 NSLog(@"正在使用手机网络上网"); 68 } else { 69 NSLog(@"没有网络"); 70 } 71 } 72 73 @end 74
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。