可达性总是返回NotReach

时间:2014-09-26 04:27:23

标签: ios objective-c

我使用可达性来检测网络变化。第一次使用wifi可用。但随后我关闭了wifi然后打开,它总是返回NotReach

Reachability *internetChecker;
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(myMethod:) name:kReachabilityChangedNotification object:nil];
internetChecker = [Reachability reachabilityWithHostName:@"www.24h.com.vn"];
[internetChecker startNotifier];

在mymethod中:

NetworkStatus status = [internetChecker currentReachabilityStatus];
switch (status) {
    case NotReachable:
    {
    NSLog(@"no wifi");
        break;
    }
default:
{
    NSLog(@"wifi");
    break;
}

}

3 个答案:

答案 0 :(得分:0)

尝试以下解决方案

+ (BOOL)checkInternetConnection
{
    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
    if (remoteHostStatus == NotReachable)
    {
        return FALSE;
    }
    else
    {
        return TRUE;
    }
}

你必须修改这一行

Reachability * internetChecker = [Reachability reachabilityForInternetConnection];

希望它可以帮助你......!

答案 1 :(得分:0)

您是否拥有互联网和主机的单独可达性属性?

@property (nonatomic) Reachability *internetReachability;
@property (nonatomic) Reachability *hostReachability;

然后这样做:

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

self.internetReachability = [Reachability reachabilityForInternetConnection];
[self.internetReachability startNotifier];
[self updateInterfaceWithReachability:self.internetReachability];

self.hostReachability = [Reachability reachabilityWithHostName:@"www.24h.com.vn"];
[self.hostReachability startNotifier];
[self updateInterfaceWithReachability:self.hostReachability];

然后 myMethod:

- (void)myMethod:(NSNotification *)note
{
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
    [self updateInterfaceWithReachability:curReach];
}

updateInterfaceWithReachability

- (void)updateInterfaceWithReachability:(Reachability *)reachability {
     NetworkStatus netStatus = [reachability currentReachabilityStatus];

     if (reachability == self.internetReachability) {
        switch (netStatus) {
             case NotReachable:
                 NSLog(@"no internet");
                 break;
            case ReachableViaWWAN:
            case ReachableViaWiFi:
                 NSLog(@"with internet");
                 break;
        }
     }

     if (reachability == self.hostReachability) {
         switch (netStatus) {
             case NotReachable:
                 NSLog(@"www.24h.com.vn unavailable");
                 break;
             case ReachableViaWWAN:
             case ReachableViaWiFi:
                 NSLog(@"www.24h.com.vn available");
                 break;
         }
     }

答案 2 :(得分:0)

完成!我不知道如何,但它似乎通知中心只检测网络变化。当它注意到状态仍然是NotReachable时。所以我在2s延迟后检查网络。它有效!