iOS实时监测网络状况

网络连接与否,直接关系到获取数据的方式,当没网时,需要从本地获取缓存数据,有wifi,展示高清图片,无wifi时,只能展示缩略图。因此,在展示数据时,首要做的就是判断网络,判断网络苹果提供了这个Reachability类,需要自己添加到工程里。另外需要添加库SystemConfiguration.framework这个库

苹果提供的Reachability类的下载地址

https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip

下面是代码的实现

AppDelegate.h文件

 

#import <UIKit/UIKit.h>

#import "Reachability.h"

 

@interface AppDelegate : UIResponder <UIApplicationDelegate>

 

@property (strong, nonatomic) UIWindow *window;

//判断网络

@property(nonatomic,strong)Reachability*hostReach;

//记录网络状态

@property(nonatomic,strong)NSString*isReachable;

 

@end

 

 

AppDelegate.m文件

 

 

#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window = [[UIWindow alloc] init];

    self.window.frame = [UIScreen mainScreen].bounds;

    self.window.backgroundColor = [UIColor whiteColor];

    [self.window makeKeyAndVisible];

     //开启网络状况的监听

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

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

    [self.hostReach startNotifier];  //开始监听,会启动一个run loop

    return YES;

}

//网络链接改变时会调用的方法

-(void)reachabilityChanged:(NSNotification *)notification

{

    Reachability *currReach = [notification object];

    NSParameterAssert([currReach isKindOfClass:[Reachability class]]);

    //对连接改变做出响应处理动作

    NetworkStatus status = [currReach currentReachabilityStatus];

    //如果没有连接到网络就弹出提醒实况

    if(status == NotReachable)

    {

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络无连接" message:@"暂时无法访问,请打开网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];

        [alert show];

        self.isReachable =@"NONet";

    }else if(status==ReachableViaWWAN){

    //非wifi状态

        self.isReachable=@"YES+WWAN";

        

    }else{

        //wifi状态

        self.isReachable =@"YES+WIFI";

    }

 }

 

在其他类里面调用的时候加入如下代码

可以在网络连接状态下再判断wifi状态,这里我就省略了

   

 AppDelegate *appDlg = (AppDelegate *)[[UIApplication sharedApplication] delegate];

     if(![appDlg.isReachable isEqualToString:@"NONet"])

     {

     NSLog(@"网络已连接");//执行网络正常时的代码 

     }

     else

     {

     NSLog(@"网络连接异常");//执行网络无连接时的代码

     }

 

 

使用的时候请注意,self.hostReach 一定要初始化,要不然监听的方法是不会走的,也无法进行监听

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值