如何检测网络的变化与可达性? [英] How to detect change in network with Reachability?

查看:128
本文介绍了如何检测网络的变化与可达性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用以下方式检查 viewDidLoad 上的网络连接:

   - (BOOL)reachable {
ReachabilityDRC * r = [ReachabilityDRC reachabilityWithHostName:@google.com];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if(internetStatus == NotReachable){
return NO;
}
return YES;
}

但我也希望在网络发生变化时



如何调整我的方法来做这样的事情?

$ b $另一个可能的解决方案是在应用程序didfinishlaunching中添加一个NS通知:

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

并在checkForReachability方法中执行:

 可达性* reachability = [Reachability reachabilityForInternetConnection]; 
[reachability startNotifier];

NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];

if(remoteHostStatus == NotReachable){
//做某事
}
else if(remoteHostStatus == ReachableViaWiFi){
//做某事
}
else {

//另做别的
}


I'm currently checking network connection on viewDidLoad using this:

-(BOOL)reachable {
    ReachabilityDRC *r = [ReachabilityDRC reachabilityWithHostName:@"google.com"];
    NetworkStatus internetStatus = [r currentReachabilityStatus];
    if(internetStatus == NotReachable) {
        return NO;
    }
    return YES;
}

But I also want to be notified if there is a change of network, such as wifi dropped, or wifi is back, so I can make changes accordingly.

How can I adjust my method to do something like that?

解决方案

Another possible solution is to add a NS Notification in "application didfinishlaunching":

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

and in checkForReachability method do this:

    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    [reachability startNotifier];

    NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];

    if(remoteHostStatus == NotReachable) {
        //Do something
    }
     else if (remoteHostStatus == ReachableViaWiFi) {
    // Do something
 }
    else{

// Else do something else
}

这篇关于如何检测网络的变化与可达性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆