0

假设我实际上有互联网连接,我使用此代码来了解设备是否通过 WiFi 连接:

+ (BOOL)hasWiFiConnection {

    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    [reachability startNotifier];

    NetworkStatus status = [reachability currentReachabilityStatus];

    if (status == ReachableViaWiFi) {

        return YES;

    } else {

        return NO;
    }
}

该代码运行速度快吗?

我在为图片生成 URL 时使用它(这样我就知道我是加载高分辨率图片还是低分辨率图片)。这些图片显示在列表视图中(每行 3 个)。当我滚动列表时,该函数每秒调用几次。那效率高吗?

4

1 回答 1

2

如果您不想使用可达性类,请使用以下代码。

        @interface CMLNetworkManager : NSObject
        +(CMLNetworkManager *) sharedInstance;

       -(BOOL) hasConnectivity;
          @end

执行

         @implementation CMLNetworkManager

         +(CMLNetworkManager *) sharedInstance {
     static CMLNetworkManager *_instance = nil;
@synchronized(self) {
    if(_instance == nil) {
        _instance = [[super alloc] init];
    }
}
return _instance;
 }

   -(BOOL) hasConnectivity {
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;

SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);
if(reachability != NULL) {
    //NetworkStatus retVal = NotReachable;
    SCNetworkReachabilityFlags flags;
    if (SCNetworkReachabilityGetFlags(reachability, &flags)) {
        if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
        {
            // if target host is not reachable
            return NO;
        }

        if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
        {
            // if target host is reachable and no connection is required
            //  then we'll assume (for now) that your on Wi-Fi
            return YES;
        }


        if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
             (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
        {
            // ... and the connection is on-demand (or on-traffic) if the
            //     calling application is using the CFSocketStream or higher APIs

            if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
            {
                // ... and no [user] intervention is needed
                return YES;
            }
        }

        if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
        {
            // ... but WWAN connections are OK if the calling application
            //     is using the CFNetwork (CFSocketStream?) APIs.
            return YES;
        }
    }
}

return NO;
  }
  @end

使用类共享实例的 bool 方法是你想要的

于 2013-02-19T14:19:12.103 回答