3

今天,我公开了我的 Beta 版应用程序。我在一家酒店,还没有获得 WiFi 的访问代码。在测试可达性时,我注意到它并没有像它应该的那样失败。它已连接到 WiFi,但实际上什么都无法访问,因为我没有登录。这个用例应该包含在reachabilityWithHostname中。这是我的代码:

在 AppDelegate.h 中:

@interface AppDelegate : UIResponder <UIApplicationDelegate> {

    Reachability* hostReach;
    Reachability* internetReach;
    Reachability* wifiReach;
}

在 AppDelegate.m 中:

    internetReach = [Reachability reachabilityForInternetConnection];
    [internetReach startNotifier];

    wifiReach = [Reachability reachabilityForLocalWiFi];
    [wifiReach startNotifier];

    hostReach = [Reachability reachabilityWithHostname: @"http://www.google.com"];
    [hostReach connectionRequired];
    [hostReach startNotifier];

在需要连接的模块中:

- (BOOL) isInternetReachable
{
    Reachability *currentReach = [Reachability reachabilityForInternetConnection];
    NetworkStatus netStatus = [currentReach currentReachabilityStatus];


    return (netStatus == ReachableViaWiFi || netStatus == ReachableViaWWAN);
}

有谁知道如何涵盖这种情况?

4

4 回答 4

3

您使用的可达性错误。Apple 的文档非常糟糕,因此请忽略它。

诀窍是在不先咨询可达性的情况下尝试建立网络连接。NSURLConnection 将启动无线电并根据需要建立连接。当然,一定要处理错误。

当网络在离线后重新在线时,可达性仍然有用。如果您有事先无法发送/接收的信息,您可以在此时重试连接。

此外,您不应该在主线程上调用 Reachability。在质量差的网络上,尤其是丢包率高或 DNS 损坏的网络上,Reachability 会挂起您的应用程序超过 20 秒,系统会杀死您。

于 2013-03-09T03:18:47.707 回答
3
...
[Reachability reachabilityWithHostname: @"http://www.google.com"]
...

根据Apple 的文档,您应该使用主机名(不带http://)。

于 2013-03-09T03:07:19.863 回答
3

我使用可达性来证明网络层。当它应该没问题时,我会尝试从我的服务器加载一个字节的文件来确定。性能还可以。

BOOL isOnline =  [[[RKClient sharedClient] reachabilityObserver] isReachabilityDetermined] != YES || [[RKClient sharedClient] isNetworkReachable];

    if(isOnline){
        NSData *data = [NSData dataWithContentsOfURL:[[URLManager sharedInstance]availabilityCheckURL]];

        NSString *strTemp = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
        isOnline = [strTemp isEqualToString:@"1"];
    }
于 2013-08-20T12:22:06.983 回答
0

Reachability 示例使用SystemConfiguration 的 Reachability API

当应用程序发送到网络堆栈的数据包可以离开本地设备时,远程主机被认为是可达的。可达性并不能保证数据包会真正被主机接收。

它可能会做两件事:

  • (重复?)将主机名解析为 IP 地址。
  • 观察路由表并在该 IP 的“可达性”发生变化时发送回调。

对于强制门户(又名 Wi-Fi 登录页面),http://www.example.com必须在您的网络浏览器中显示为将您重定向到登录页面的站点;这意味着www.example.com 必须解析(无论是否为其实际 IP),并且该 IP 必须有一个站点才能将您重定向到登录页面。

可达性主要用于检测飞行模式或与 Wi-Fi 断开连接等情况。

于 2013-03-09T03:25:53.057 回答