【问题标题】:Checking Network Availability检查网络可用性
【发布时间】:2012-09-01 22:44:37
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: iphone network-connection


    【解决方案1】:

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

    并检查此链接。

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

    【讨论】:

    【解决方案2】:

    使用可达性”

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

    #import "Reachability.h"
    -(BOOL)isHostAvailable
    {
        //return NO; // force for offline testing
        Reachability *hostReach = [Reachability reachabilityForInternetConnection];
        NetworkStatus netStatus = [hostReach currentReachabilityStatus];
        return !(netStatus == NotReachable);
    }
    

    【讨论】:

    • 谢谢你的回答.....但是我的应用程序可以跟踪网络状态的变化吗??
    【解决方案3】:

    使用此标志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];
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多