0

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

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

我需要找出网络状态何时发生变化(即网络状态从可达变为不可达,反之亦然)。

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

4

3 回答 3

1

我建议使用 Apple 的 Reachability 类。是Apple的示例应用程序。

并检查此链接。

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

于 2012-09-08T06:11:23.127 回答
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];
        }
    }
}
于 2012-09-25T10:06:48.810 回答
-1

使用可达性”

在应用程序委托中添加泛洪方法,以便您可以在项目中的任何软件中使用此方法

#import "Reachability.h"
-(BOOL)isHostAvailable
{
    //return NO; // force for offline testing
    Reachability *hostReach = [Reachability reachabilityForInternetConnection];
    NetworkStatus netStatus = [hostReach currentReachabilityStatus];
    return !(netStatus == NotReachable);
}
于 2012-09-08T06:58:14.430 回答