使用iOS SDK检查网络连接

12 浏览
0 Comments

使用iOS SDK检查网络连接

这个问题已经在这里有答案了:

如何在iOS或macOS上检查活动的Internet连接?

使用iOS SDK检查Internet连接的最佳方法是什么?

admin 更改状态以发布 2023年5月22日
0
0 Comments

Reachability有许多多余的东西,而且它还没有为ARC更新。

这是我用纯C的解决方案。大部分的代码直接从Reachability中提取,但只保留了必要的部分。我只想让它返回是否有互联网连接,但通过注释可以了解它是否基于找到Wifi或蜂窝网络来返回“YES”。

在继续共享代码之前,最后注意一点:您需要进入构建目标,选择构建阶段选项卡,并将“SystemConfiguration.framework”添加到“链接二进制文件与库”列表中。

#import 
#import 
#import 
BOOL networkReachable()
{
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
    SCNetworkReachabilityRef reachabilityRef = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *) &zeroAddress);
    SCNetworkReachabilityFlags flags;
    if (SCNetworkReachabilityGetFlags(reachabilityRef, &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; // This is a wifi connection.
        }
        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; // This is a wifi connection.
            }
        }
        if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN) {
            // ... but WWAN connections are OK if the calling application
            //     is using the CFNetwork (CFSocketStream?) APIs.
            return YES; // This is a cellular connection.
        }
    }
    return NO;
}

0
0 Comments

最好的方法是使用网络可达性的代码。在此处查看苹果的示例代码。这里有很多方便的方法来检查互联网的可用性、Wifi/WAN连接等。

例如:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkChanged:) name:kReachabilityChangedNotification object:nil];
reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];
- (void)networkChanged:(NSNotification *)notification
{
  NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
  if(remoteHostStatus == NotReachable) { NSLog(@"not reachable");}
  else if (remoteHostStatus == ReachableViaWiFiNetwork) { NSLog(@"wifi"); }
  else if (remoteHostStatus == ReachableViaCarrierDataNetwork) { NSLog(@"carrier"); }
}

0