gpt4 book ai didi

ios - iOS中单点的互联网连接方法?

转载 作者:行者123 更新时间:2023-11-28 22:20:46 24 4
gpt4 key购买 nike

我的应用程序中有这个方法来检查互联网。

/*
Connectivity testing code pulled from Apple's Reachability Example: http://developer.apple.com/library/ios/#samplecode/Reachability
*/
-(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;
}

我必须将这个方法粘贴到每个类上并像这样检查互联网

if([self hasConnectivity] == YES){

我想把这个方法放在一个类中,就像我把宏放在 Constants.h 或 .pch 文件中一样。

有什么办法(除了委托(delegate),因为我不想那么多地使用委托(delegate))。

谢谢

最佳答案

-(BOOL)hasConnectivity 更改为 +(BOOL)hasConnectivity(这会将一个实例方法转换为一个 方法)。将其添加到名为 Reachability 的类中。将 Reachability.h 添加到您的 .pch 中。现在调用 [Reachability hasConnectivity] 并从您应用的任何位置检查其返回值。繁荣。

关于ios - iOS中单点的互联网连接方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20476089/

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