0

我目前正在编写一些代码来确定是否可以在 Mac 或 iOS 上进行网络请求。

在我被告知查看 Apple 提供的 Reachability 类之前,我只想指出,即使使用它们,我也会得到相同的结果。所以,相反,我想我会写我自己的,因为它确实是我所需要的。

我已经启动了一个与 Apple 完全一样的可达性对象:

+ (Reachability*) reachabilityForInternetConnection;
{
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
    return [self reachabilityWithAddress: &zeroAddress];
}

然后调用[networkStatusForFlags:flags](或其在我的代码中的等价物),我有以下内容:

NSLog(@"Reachability Flag Status: %c%c %c%c%c%c%c%c%c\n",
      (flags & kSCNetworkReachabilityFlagsIsWWAN)               ? 'W' : '-',
      (flags & kSCNetworkReachabilityFlagsReachable)            ? 'R' : '-',

      (flags & kSCNetworkReachabilityFlagsTransientConnection)  ? 't' : '-',
      (flags & kSCNetworkReachabilityFlagsConnectionRequired)   ? 'c' : '-',
      (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic)  ? 'C' : '-',
      (flags & kSCNetworkReachabilityFlagsInterventionRequired) ? 'i' : '-',
      (flags & kSCNetworkReachabilityFlagsConnectionOnDemand)   ? 'D' : '-',
      (flags & kSCNetworkReachabilityFlagsIsLocalAddress)       ? 'l' : '-',
      (flags & kSCNetworkReachabilityFlagsIsDirect)             ? 'd' : '-'
      );

BOOL thereIsInternetAccess = NO;

if ((flags & kSCNetworkReachabilityFlagsReachable) != 0 && (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
{
    thereIsInternetAccess = YES;
}
else
{
    thereIsInternetAccess = NO;
}

无论我的 Mac 的 Wifi 是打开还是关闭,我都会将以下内容输出到控制台Reachability Flag Status: -R -----l-,这对我来说表明互联网存在(由于R被标记)

我错过了什么吗?任何帮助将不胜感激。

NOTE: I'm using the iOS Simulator. Don't think that should matter though.

4

1 回答 1

0

The iOS Simulator doesn't work as you'd expect it to.

Using the System Configuration framework for network reachability does notify when the Mac's network status has been updated using the registered call back (SCNetworkReachabilitySetCallback). However, from my testing it appears the flags are not returned back correctly every time. Using the same code on a Mac with a mac app target, or on an iOS Device, the code runs with the expected results.

Yet another reason why the simulator should never be the only testing means for your app.

于 2014-05-19T09:27:31.700 回答