iOS - 监测网络状态

来源:互联网 发布:淘宝二合一口令api 编辑:程序博客网 时间:2024/04/28 00:42

一、说明
在网络应用中,需要对用户设备的网络状态进行实时监控,有两个目的:(1)让用户了解自己的网络状态,防止一些误会(比如怪应用无能)(2)根据用户的网络状态进行智能处理,节省用户流量,提高用户体验
 WIFI\3G网络:自动下载高清图片
 低速网络:只下载缩略图  
   没有网络:只显示离线的缓存数据
苹果官方提供了一个叫Reachability的示例程序,便于开发者检测网络状态
二、监测网络状态 Reachability的使用步骤
添加框架SystemConfiguration.framework
下载苹果的示例程序后,将俩个文件提取出来加入工程
并引入头文件 #import "Reachability.h"

示例代码:

#import "ViewController.h"#import "Reachability.h"@interface ViewController ()@property (nonatomic,strong)Reachability *reach;@end@implementation ViewController- (void)viewDidLoad{    [super viewDidLoad];    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(netWorkStateChange) name:kReachabilityChangedNotification object:nil];    self.reach = [Reachability reachabilityForInternetConnection];    [self.reach startNotifier];}- (void)netWorkStateChange{    [self checkNetWorkState];    }- (void)checkNetWorkState{//    监测WIFI    Reachability *wifi = [Reachability reachabilityForLocalWiFi];    //    监测手机能否上网    Reachability *connect = [Reachability reachabilityForInternetConnection];        if ([wifi currentReachabilityStatus] != NotReachable) {        NSLog(@"有WIFI");    }else if ([connect currentReachabilityStatus] != NotReachable){        NSLog(@"手机流量上网");    }else{        NSLog(@"没用网络");    }//    用手机流量上网//    [wifi currentReachabilityStatus] == NotReachable;//    [connect currentReachabilityStatus] != NotReachable;    //    用WIFI上网//    [wifi currentReachabilityStatus] != NotReachable;//    [connect currentReachabilityStatus] != NotReachable;    //    没用网络//    [wifi currentReachabilityStatus] == NotReachable;//    [connect currentReachabilityStatus] == NotReachable;}- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{    [[NSNotificationCenter defaultCenter] postNotificationName:kReachabilityChangedNotification object:nil];    }- (void)dealloc{    [self.reach stopNotifier];    [[NSNotificationCenter defaultCenter]removeObserver:self];}@end






0 0
原创粉丝点击