使用 iOS SDK 检查互联网连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13735611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 21:26:20  来源:igfitidea点击:

Check for Internet connection using the iOS SDK

iphoneobjective-ciosipadconnection

提问by user831098

Which is the best way to check the Internet connection using the iOS SDK?

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

回答by iDev

Best way is to use Reachability code. Check here for apple sample code. That has a lot of convenience methods to check internet availability, Wifi/WAN connectivity check etc..

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

For eg:-

例如:-

[[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"); }
}

回答by ArtOfWarfare

Reachability has a lot more to it than it needs, plus it hasn't been updated for ARC yet.

可达性比它需要的要多得多,而且它还没有针对 ARC 进行更新。

Here's my solution in pure C. Much of the code was taken directly from Reachability, but distilled down to only what is necessary. I only wanted it to return whether there was or wasn't an internet connection, but you can read from the comments whether it's returning YES based on having found a Wifi or a Cellular network.

这是我在纯 C 中的解决方案。大部分代码直接取自 Reachability,但仅浓缩为必要的部分。我只希望它返回是否有互联网连接,但是您可以从评论中阅读是否根据找到 Wifi 或蜂窝网络返回 YES。

One last note before proceeding to share the code: You need to go into your build target, select the build phases tab, and add "SystemConfiguration.framework" to the "Link Binary With Libraries" list.

在继续共享代码之前的最后一个注意事项:您需要进入构建目标,选择构建阶段选项卡,并将“SystemConfiguration.framework”添加到“Link Binary With Libraries”列表中。

#import <CoreFoundation/CoreFoundation.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <netdb.h>

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;
}

回答by Darkngs

Try this code:

试试这个代码:

- (BOOL)connectedToInternet
{
   NSURL *url=[NSURL URLWithString:@"http://www.google.com"];
   NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
   [request setHTTPMethod:@"HEAD"];
   NSHTTPURLResponse *response;
   [NSURLConnection sendSynchronousRequest:request returningResponse:&response error: NULL];

   return ([response statusCode]==200)?YES:NO;
}