检查网络可用性

时间:2012-09-08 06:00:09

标签: iphone network-connection

我使用可访问性类来检查我的应用程序中的网络连接...

Reachability *reach = [Reachability reachabilityForInternetConnection]; 
    NetworkStatus netStatus = [reach currentReachabilityStatus];    
    if (netStatus==NotReachable)
    {
        NSLog(@"NR");
    }

我需要找到网络状态发生变化的时间(即当网络状态从可达到变为无法到达时,反之亦然)。

有没有代表发现这个想法,有什么建议吗?

3 个答案:

答案 0 :(得分:1)

我建议使用Apple的Reachability类。 Here是Apple的示例App。

并查看此链接。

  

http://www.switchonthecode.com/tutorials/iphone-snippet-detecting-network-status

答案 1 :(得分:0)

使用此标记kReachabilityChangedNotification查找网络状态的变化并将其传递给NSNotificationCenter

以下是代码:

NSString *host = @"https://www.apple.com"; // Put your host here

        // Set up host reach property
       hostReach = [Reachability reachabilityWithHostname:host];

                          // Enable the status notifications
                          [[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
                           [hostReach startNotifier];

   - (void) reachabilityChanged: (NSNotification* )note
{
    Reachability *reachability = [note object];
    NSParameterAssert([reachability isKindOfClass:[Reachability class]]);
    if (reachability == hostReach) {
        Reachability *reach = [Reachability reachabilityForInternetConnection]; 
        NetworkStatus netStatus = [reach currentReachabilityStatus];    
        if (netStatus==NotReachable)
        {
            NSLog(@"notreacheable");
        }
        else {
            NSLog(@"reacheable");
            [[NSNotificationCenter defaultCenter]postNotificationName:@"startUpdatingTable" object:nil];
        }
    }
}

答案 2 :(得分:-1)

使用可达性“

在app delegate中添加flooding方法,这样你就可以在项目

中使用这个方法
#import "Reachability.h"
-(BOOL)isHostAvailable
{
    //return NO; // force for offline testing
    Reachability *hostReach = [Reachability reachabilityForInternetConnection];
    NetworkStatus netStatus = [hostReach currentReachabilityStatus];
    return !(netStatus == NotReachable);
}
相关问题