13

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

4

3 回答 3

36

最好的方法是使用可达性代码。在此处查看苹果示例代码。它有很多方便的方法来检查互联网可用性、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"); }
}
于 2012-12-06T01:42:10.550 回答
13

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

这是我用纯 C 语言编写的解决方案。大部分代码直接取自 Reachability,但只提炼出必要的部分。我只希望它返回是否存在互联网连接,但您可以从评论中读取它是否基于找到 Wifi 或蜂窝网络返回 YES。

在继续共享代码之前的最后一个注意事项:您需要进入构建目标,选择构建阶段选项卡,然后将“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;
}
于 2013-08-06T03:48:54.200 回答
10

试试这个代码:

- (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;
}
于 2013-02-27T15:30:29.080 回答