=简易实现=网络实时监控

添加第三方Reachability 加入需要添加Systemconfiguration.framework


#import"AppDelegate.h"

didFinishLaunchingWithOptions中添加

 /****************************************************/
    
    //网络检测****************
    [[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
    hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    [hostReach startNotifier];
    
    /****************************************************/

- (void)reachabilityChanged:(NSNotification*)note{
    NSLog(@"==_==");
    Reachability* curReach= [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    [self updateInterfaceWithReachability:curReach];
}
// 更新网络状态
- (void)updateInterfaceWithReachability: (Reachability*)curReach
{
    //对连接改变做出响应的处理动作。
    
    NetworkStatus status=[curReach currentReachabilityStatus];
    NSUserDefaults * user =[NSUserDefaults standardUserDefaults];
    if (status== NotReachable) { //没有连接到网络就弹出提实况
        [user removeObjectForKey:@"network"];
        [user setBool:NO forKey:@"network"];
        
        [self showAlert:@"网络连接被断开"];
    }else{
        [user removeObjectForKey:@"network"];
        [user setBool:YES forKey:@"network"];
        
        [self showAlert:@"网络连接成功"];
    }
    NSLog(@"%@",[user objectForKey:@"network"]);
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"network" object:user];
}

-(void)showAlert:(NSString *)message{
    UIAlertView*alert= [[UIAlertView alloc] initWithTitle:message
                                                                  message:nil delegate:nil
                                                      cancelButtonTitle:@"确定"otherButtonTitles:nil];
    [alert show];
}

#import"ViewController.h"


在此viewDidLoad中添加注册通知

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(network:) name:@"network" object:nil];
   
}

-(void)network:(NSNotification *)note{
     id obj = [note object];//获取到传递的对象
    NSLog(@"---%@-----",[obj objectForKey:@"network"]);
    BOOL isOpen = [[obj objectForKey:@"network"] intValue];
    NSLog(@"%d",isOpen);
    if (isOpen) {
        NSLog(@"--有网络--");
    }else{
        NSLog(@"--无网络--");
    }
}


最近学会的一个怎么实现网络实时监控的简易方法。欢迎大家能指出其中不恰当的地方。





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值