gpt4 book ai didi

ios - 在 iOS 中检查互联网可达性是否有效?

转载 作者:行者123 更新时间:2023-11-28 22:39:34 25 4
gpt4 key购买 nike

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

+ (BOOL)hasWiFiConnection {

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

NetworkStatus status = [reachability currentReachabilityStatus];

if (status == ReachableViaWiFi) {

return YES;

} else {

return NO;
}
}

该代码运行速度快吗?

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

最佳答案

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

        @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 方法

关于ios - 在 iOS 中检查互联网可达性是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14959234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com