我想检查一下我是否在使用Cocoa Touch库的iOS上或在使用Cocoa库的macOS上建立了Internet连接。

我想出了一种使用NSURL做到这一点的方法。 我这样做的方式似乎有点不可靠(因为即使Google可能有一天会倒闭,依赖第三方也似乎很糟糕),而且我可以检查一下是否有其他网站的响应(如果Google没有响应),确实看起来很浪费,而且对我的应用程序来说也没有不必要的开销。

- (BOOL) connectedToInternet
{NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];return ( URLString != NULL ) ? YES : NO;
}

我做的不stringWithContentsOfURL (更不用说在iOS 3.0和macOS 10.4中不推荐使用stringWithContentsOfURL ),如果是的话,有什么更好的方法来做到这一点?


#1楼

这里有一个美观的,使用ARC和GCD的可达性现代化方案:

可达性


#2楼

您可以使用ach( 在此处提供 )使用可Reachability

#import "Reachability.h"- (BOOL)networkConnection {return [[Reachability reachabilityWithHostName:@"www.google.com"] currentReachabilityStatus];
}if ([self networkConnection] == NotReachable) { /* No Network */ } else { /* Network */ } //Use ReachableViaWiFi / ReachableViaWWAN to get the type of connection.

#3楼

这是一个非常简单的答案:

NSURL *scriptUrl = [NSURL URLWithString:@"http://www.google.com/m"];
NSData *data = [NSData dataWithContentsOfURL:scriptUrl];
if (data)NSLog(@"Device is connected to the Internet");
elseNSLog(@"Device is not connected to the Internet");

该网址应指向一个非常小的网站。 我在这里使用Google的移动网站,但是如果我有一个可靠的网络服务器,我将上传一个只有一个字符的小文件,以实现最大速度。

如果要检查设备是否以某种方式连接到Internet,我绝对会建议您使用此简单的解决方案。 如果您需要了解用户的连接方式,则可以使用“可达性”。

注意:加载网站时,这会暂时阻止您的线程。 就我而言,这不是问题,但您应该考虑一下(Brad指出了这一点)。


#4楼

苹果提供了一个示例应用程序,它可以完成以下操作:

可达性


#5楼

Apple提供了示例代码来检查不同类型的网络可用性。 另外,iPhone开发人员手册中也有一个示例 。

注意:有关使用Apple可达性代码的信息,请参阅@KHG关于此答案的评论。


#6楼

我在此讨论中使用了代码,而且看起来工作正常(阅读整个线程!)。

我还没有对每种可能的连接方式(例如临时Wi-Fi)进行详尽的测试。


#7楼

这曾经是正确的答案,但现在已经过时,因为您应该订阅通知以获取可达性。 此方法同步检查:


您可以使用Apple的Reachability类。 它还将允许您检查是否启用了Wi-Fi:

Reachability* reachability = [Reachability sharedReachability];
[reachability setHostName:@"www.example.com"];    // Set your host name here
NetworkStatus remoteHostStatus = [reachability remoteHostStatus];if (remoteHostStatus == NotReachable) { }
else if (remoteHostStatus == ReachableViaWiFiNetwork) { }
else if (remoteHostStatus == ReachableViaCarrierDataNetwork) { }

SDK并未随附Reachability类,而是该Apple示例应用程序的一部分。 只需下载它,然后将Reachability.h / m复制到您的项目中即可。 同样,您必须将SystemConfiguration框架添加到您的项目中。


#8楼

- (void)viewWillAppear:(BOOL)animated
{NSString *URL = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];return (URL != NULL ) ? YES : NO;
}

或使用Reachability类

有两种方法可以使用iPhone SDK检查Internet可用性:

1.检查Google页面是否打开。

2.可达性等级

有关更多信息,请参阅可达性 (Apple Developer)。


#9楼

这是我在应用程序中的操作方法:虽然200状态响应代码不能保证任何事情,但对我来说足够稳定。 这不需要像这里发布的NSData答案那样多的负载,因为我只是检查HEAD响应。

SWIFT代码

func checkInternet(flag:Bool, completionHandler:(internet:Bool) -> Void)
{UIApplication.sharedApplication().networkActivityIndicatorVisible = truelet url = NSURL(string: "http://www.google.com/")let request = NSMutableURLRequest(URL: url!)request.HTTPMethod = "HEAD"request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheDatarequest.timeoutInterval = 10.0NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue.mainQueue(), completionHandler:{(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void inUIApplication.sharedApplication().networkActivityIndicatorVisible = falselet rsp = response as! NSHTTPURLResponse?completionHandler(internet:rsp?.statusCode == 200)})
}func yourMethod()
{self.checkInternet(false, completionHandler:{(internet:Bool) -> Void inif (internet){// "Internet" aka Google URL reachable}else{// No "Internet" aka Google URL un-reachable}})
}

Objective-C代码

typedef void(^connection)(BOOL);- (void)checkInternet:(connection)block
{NSURL *url = [NSURL URLWithString:@"http://www.google.com/"];NSMutableURLRequest *headRequest = [NSMutableURLRequest requestWithURL:url];headRequest.HTTPMethod = @"HEAD";NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration ephemeralSessionConfiguration];defaultConfigObject.timeoutIntervalForResource = 10.0;defaultConfigObject.requestCachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue: [NSOperationQueue mainQueue]];NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:headRequestcompletionHandler:^(NSData *data, NSURLResponse *response, NSError *error){if (!error && response){block([(NSHTTPURLResponse *)response statusCode] == 200);}}];[dataTask resume];
}- (void)yourMethod
{[self checkInternet:^(BOOL internet){if (internet){// "Internet" aka Google URL reachable}else{// No "Internet" aka Google URL un-reachable}}];
}

#10楼

如果您使用的是AFNetworking ,则可以使用其自己的实现来实现Internet可达性状态。

使用AFNetworking的最佳方法是对AFHTTPClient类进行子类化,并使用该类进行网络连接。

使用此方法的优点之一是,当可达性状态发生更改时,可以使用blocks来设置所需的行为。 假设我已经创建的单子AFHTTPClient (作为对“子类钞”说AFNetworking文档 )命名BKHTTPClient ,我会做一些事情,如:

BKHTTPClient *httpClient = [BKHTTPClient sharedClient];
[httpClient setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
{if (status == AFNetworkReachabilityStatusNotReachable) {// Not reachable}else{// Reachable}
}];

您还可以专门使用AFNetworkReachabilityStatusReachableViaWWANAFNetworkReachabilityStatusReachableViaWiFi枚举来检查Wi-Fi或WLAN连接( 此处更多信息 )。


#11楼

-(void)newtworkType {NSArray *subviews = [[[[UIApplication sharedApplication] valueForKey:@"statusBar"] valueForKey:@"foregroundView"]subviews];
NSNumber *dataNetworkItemView = nil;for (id subview in subviews) {if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {dataNetworkItemView = subview;break;}
}switch ([[dataNetworkItemView valueForKey:@"dataNetworkType"]integerValue]) {case 0:NSLog(@"No wifi or cellular");break;case 1:NSLog(@"2G");break;case 2:NSLog(@"3G");break;case 3:NSLog(@"4G");break;case 4:NSLog(@"LTE");break;case 5:NSLog(@"Wifi");break;default:break;
}
}

#12楼

首先下载可到达性类,然后在Xcode中放入reachability.h和reachabilty.m文件。

最好的方法是制作一个通用的Functions类(NSObject),以便可以在任何类中使用它。 这是网络连接可达性检查的两种方法:

+(BOOL) reachabiltyCheck
{NSLog(@"reachabiltyCheck");BOOL status =YES;[[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(reachabilityChanged:)name:kReachabilityChangedNotificationobject:nil];Reachability * reach = [Reachability reachabilityForInternetConnection];NSLog(@"status : %d",[reach currentReachabilityStatus]);if([reach currentReachabilityStatus]==0){status = NO;NSLog(@"network not connected");}reach.reachableBlock = ^(Reachability * reachability){dispatch_async(dispatch_get_main_queue(), ^{});};reach.unreachableBlock = ^(Reachability * reachability){dispatch_async(dispatch_get_main_queue(), ^{});};[reach startNotifier];return status;
}+(BOOL)reachabilityChanged:(NSNotification*)note
{BOOL status =YES;NSLog(@"reachabilityChanged");Reachability * reach = [note object];NetworkStatus netStatus = [reach currentReachabilityStatus];switch (netStatus){case NotReachable:{status = NO;NSLog(@"Not Reachable");}break;default:{if (!isSyncingReportPulseFlag){status = YES;isSyncingReportPulseFlag = TRUE;[DatabaseHandler checkForFailedReportStatusAndReSync];}}break;}return status;
}+ (BOOL) connectedToNetwork
{// Create zero addystruct sockaddr_in zeroAddress;bzero(&zeroAddress, sizeof(zeroAddress));zeroAddress.sin_len = sizeof(zeroAddress);zeroAddress.sin_family = AF_INET;// Recover reachability flagsSCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);SCNetworkReachabilityFlags flags;BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);CFRelease(defaultRouteReachability);if (!didRetrieveFlags){NSLog(@"Error. Could not recover network reachability flags");return NO;}BOOL isReachable = flags & kSCNetworkFlagsReachable;BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;BOOL nonWiFi = flags & kSCNetworkReachabilityFlagsTransientConnection;NSURL *testURL = [NSURL URLWithString:@"http://www.apple.com/"];NSURLRequest *testRequest = [NSURLRequest requestWithURL:testURL  cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0];NSURLConnection *testConnection = [[NSURLConnection alloc] initWithRequest:testRequest delegate:self];return ((isReachable && !needsConnection) || nonWiFi) ? (testConnection ? YES : NO) : NO;
}

现在,您可以通过调用此类方法检查任何类中的网络连接。


#13楼

可达性类可以确定设备是否可以使用Internet连接...

但是在访问Intranet资源的情况下:

使用可达性类对Intranet服务器执行ping操作始终返回true。

因此,在这种情况下,一种快速的解决方案是创建一个称为pingme的Web方法以及该服务上的其他Web方法。 pingme应该返回一些东西。

所以我在常用功能上写了以下方法

-(BOOL)PingServiceServer
{NSURL *url=[NSURL URLWithString:@"http://www.serveraddress/service.asmx/Ping"];NSMutableURLRequest *urlReq=[NSMutableURLRequest requestWithURL:url];[urlReq setTimeoutInterval:10];NSURLResponse *response;NSError *error = nil;NSData *receivedData = [NSURLConnection sendSynchronousRequest:urlReqreturningResponse:&responseerror:&error];NSLog(@"receivedData:%@",receivedData);if (receivedData !=nil){return YES;}else{NSLog(@"Data is null");return NO;}
}

上面的方法对我来说非常有用,因此每当我尝试向服务器发送一些数据时,我总是使用此低超时URLRequest来检查Intranet资源的可访问性。


#14楼

使用http://huytd.github.io/datatify/ 。 这比添加库和自己编写代码要容易得多。


#15楼

在您的ViewController导入Reachable.h类,并使用以下代码检查连接性

     #define hasInternetConnection [[Reachability reachabilityForInternetConnection] isReachable]if (hasInternetConnection){// To-do block}

#16楼

还有另一种使用iPhone SDK检查Internet连接的方法。

尝试为网络连接实现以下代码。

#import <SystemConfiguration/SystemConfiguration.h>
#include <netdb.h>/**Checking for network availability. It returnsYES if the network is available.
*/
+ (BOOL) connectedToNetwork
{// Create zero addystruct sockaddr_in zeroAddress;bzero(&zeroAddress, sizeof(zeroAddress));zeroAddress.sin_len = sizeof(zeroAddress);zeroAddress.sin_family = AF_INET;// Recover reachability flagsSCNetworkReachabilityRef defaultRouteReachability =SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);SCNetworkReachabilityFlags flags;BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);CFRelease(defaultRouteReachability);if (!didRetrieveFlags){printf("Error. Could not recover network reachability flags\n");return NO;}BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);return (isReachable && !needsConnection) ? YES : NO;
}

#17楼

自己做到这一点非常简单。 以下方法将起作用。 只是要确保不允许使用名称传递HTTP,HTTPS等主机名协议。

-(BOOL)hasInternetConnection:(NSString*)urlAddress
{SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [urlAddress UTF8String]);SCNetworkReachabilityFlags flags;if (!SCNetworkReachabilityGetFlags(ref, &flags)){return NO;}return flags & kSCNetworkReachabilityFlagsReachable;
}

快速,简单,无痛。


#18楼

我发现使用SimplePingHelper库非常简单。

示例代码: chrishulbert / SimplePingHelper ( GitHub )


#19楼

除了可访问性之外,您还可以使用Simple Ping帮助程序库 。 它的工作原理非常好,易于集成。


#20楼

第一 :在框架中添加CFNetwork.framework

代码ViewController.m

#import "Reachability.h"- (void)viewWillAppear:(BOOL)animated
{Reachability *r = [Reachability reachabilityWithHostName:@"www.google.com"];NetworkStatus internetStatus = [r currentReachabilityStatus];if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)){/// Create an alert if connection doesn't workUIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:@"No Internet Connection"   message:NSLocalizedString(@"InternetMessage", nil)delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];[myAlert show];[myAlert release];}else{NSLog(@"INTERNET IS CONNECT");}
}

#21楼

非常简单...。请尝试以下步骤:

步骤1:SystemConfiguration框架添加到您的项目中。


步骤2:将以下代码导入到您的header文件中。

#import <SystemConfiguration/SystemConfiguration.h>

步骤3:使用以下方法

  • 类型1:

     - (BOOL) currentNetworkStatus { [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; BOOL connected; BOOL isConnected; const char *host = "www.apple.com"; SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, host); SCNetworkReachabilityFlags flags; connected = SCNetworkReachabilityGetFlags(reachability, &flags); isConnected = NO; isConnected = connected && (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired); CFRelease(reachability); return isConnected; } 

  • 类型2:

    导入标题#import "Reachability.h"

     - (BOOL)currentNetworkStatus { Reachability *reachability = [Reachability reachabilityForInternetConnection]; NetworkStatus networkStatus = [reachability currentReachabilityStatus]; return networkStatus != NotReachable; } 

步骤4:使用方法:

- (void)CheckInternet
{BOOL network = [self currentNetworkStatus];if (network){NSLog(@"Network Available");}else{NSLog(@"No Network Available");}
}

#22楼

我认为这是最好的答案。

“是”表示已连接。 “否”表示断开连接。

#import "Reachability.h"- (BOOL)canAccessInternet
{Reachability *IsReachable = [Reachability reachabilityForInternetConnection];NetworkStatus internetStats = [IsReachable currentReachabilityStatus];if (internetStats == NotReachable){return NO;}else{return YES;}
}

#23楼

  1. 下载可达性文件https://gist.github.com/darkseed/1182373

  2. 并在框架中添加CFNetwork.framework和'SystemConfiguration.framework'

  3. 执行#import“ Reachability.h”

第一 :在框架中添加CFNetwork.framework

代码ViewController.m

- (void)viewWillAppear:(BOOL)animated
{Reachability *r = [Reachability reachabilityWithHostName:@"www.google.com"];NetworkStatus internetStatus = [r currentReachabilityStatus];if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)){/// Create an alert if connection doesn't workUIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:@"No Internet Connection"   message:NSLocalizedString(@"InternetMessage", nil)delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];[myAlert show];[myAlert release];}else{NSLog(@"INTERNET IS CONNECT");}
}

#24楼

  • 步骤1:在您的项目中添加可达性类。
  • 步骤2:导入可达性类
  • 步骤3:建立以下功能

     - (BOOL)checkNetConnection { self.internetReachability = [Reachability reachabilityForInternetConnection]; [self.internetReachability startNotifier]; NetworkStatus netStatus = [self.internetReachability currentReachabilityStatus]; switch (netStatus) { case NotReachable: { return NO; } case ReachableViaWWAN: { return YES; } case ReachableViaWiFi: { return YES; } } } 
  • 步骤4:调用以下函数:

     if (![self checkNetConnection]) { [GlobalFunctions showAlert:@"" message:@"Please connect to the Internet!" canBtntitle:nil otherBtnTitle:@"Ok"]; return; } else { Log.v("internet is connected","ok"); } 

#25楼

在(iOS)Xcode 8和Swift 3.0中检查Internet连接可用性

这是一种检查网络可用性的简单方法,就像我们的设备是否连接到任何网络一样。 我已经设法将其翻译为Swift 3.0,在这里是最终代码。 现有的Apple Reachability类和其他第三方库似乎过于复杂,无法转换为Swift。

这适用于3G,4G和WiFi连接。

不要忘记将“ SystemConfiguration.framework”添加到项目构建器。

//Create new swift class file Reachability in your project.
import SystemConfiguration
public class InternetReachability {class func isConnectedToNetwork() -> Bool {var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))zeroAddress.sin_family = sa_family_t(AF_INET)let defaultRouteReachability = withUnsafePointer(&zeroAddress) {SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue()}var flags: SCNetworkReachabilityFlags = 0if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {return false}let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0return isReachable && !needsConnection}
}// Check network connectivity from anywhere in project by using this code.if InternetReachability.isConnectedToNetwork() == true {print("Internet connection OK")} else {print("Internet connection FAILED")}

#26楼

仅可达性类已更新。 您现在可以使用:

Reachability* reachability = [Reachability reachabilityWithHostName:@"www.apple.com"];
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];if (remoteHostStatus == NotReachable) { NSLog(@"not reachable");}
else if (remoteHostStatus == ReachableViaWWAN) { NSLog(@"reachable via wwan");}
else if (remoteHostStatus == ReachableViaWiFi) { NSLog(@"reachable via wifi");}

#27楼

重要提示 :此检查应始终异步执行。 以下大多数答案是同步的,因此请小心,否则将冻结您的应用程序。


迅速

1)通过CocoaPods或迦太基安装: https : //github.com/ashleymills/Reachability.swift

2)通过闭包测试可达性

let reachability = Reachability()!reachability.whenReachable = { reachability inif reachability.connection == .wifi {print("Reachable via WiFi")} else {print("Reachable via Cellular")}
}reachability.whenUnreachable = { _ inprint("Not reachable")
}do {try reachability.startNotifier()
} catch {print("Unable to start notifier")
}

物镜

1)将SystemConfiguration框架添加到项目中,但不必担心将其包含在任何地方

2)将Tony Million的Reachability.hReachability.m版本添加到项目中(可在此处找到: https : //github.com/tonymillion/Reachability )

3)更新界面部分

#import "Reachability.h"// Add this to the interface in the .m file of your view controller
@interface MyViewController ()
{Reachability *internetReachableFoo;
}
@end

4)然后在您可以调用的视图控制器的.m文件中实现此方法

// Checks if we have an internet connection or not
- (void)testInternetConnection
{   internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"];// Internet is reachableinternetReachableFoo.reachableBlock = ^(Reachability*reach){// Update the UI on the main threaddispatch_async(dispatch_get_main_queue(), ^{NSLog(@"Yayyy, we have the interwebs!");});};// Internet is not reachableinternetReachableFoo.unreachableBlock = ^(Reachability*reach){// Update the UI on the main threaddispatch_async(dispatch_get_main_queue(), ^{NSLog(@"Someone broke the internet :(");});};[internetReachableFoo startNotifier];
}

重要说明: Reachability类是项目中最常用的类之一,因此您可能会遇到与其他项目的命名冲突。 如果发生这种情况,则必须将Reachability.hReachability.m文件对中的一个重命名为其他名称才能解决此问题。

注意:您使用的域无关紧要。 它只是测试通往任何域的网关。


#28楼

迅捷3 /迅捷4

您必须先导入

import SystemConfiguration

您可以通过以下方法检查互联网连接

func isConnectedToNetwork() -> Bool {var zeroAddress = sockaddr_in()zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))zeroAddress.sin_family = sa_family_t(AF_INET)let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress inSCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)}}var flags = SCNetworkReachabilityFlags()if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {return false}let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0return (isReachable && !needsConnection)}

#29楼

我喜欢保持简单。 我这样做的方式是:

//Class.h
#import "Reachability.h"
#import <SystemConfiguration/SystemConfiguration.h>- (BOOL)connected;//Class.m
- (BOOL)connected
{Reachability *reachability = [Reachability reachabilityForInternetConnection];NetworkStatus networkStatus = [reachability currentReachabilityStatus];return networkStatus != NotReachable;
}

然后,每当我想查看是否有连接时,就使用它:

if (![self connected]) {// Not connected
} else {// Connected. Do some Internet stuff
}

此方法无需等待更改网络状态即可完成工作。 当您要求时,它只是测试状态。


#30楼

使用Apple的Reachability代码,我创建了一个函数,该函数可以正确地检查这一点,而无需包含任何类。

在您的项目中包括SystemConfiguration.framework。

进行一些进口:

#import <sys/socket.h>
#import <netinet/in.h>
#import <SystemConfiguration/SystemConfiguration.h>

现在只需调用此函数:

/*
Connectivity testing code pulled from Apple's Reachability Example: https://developer.apple.com/library/content/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 reachablereturn 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-Fireturn 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 neededreturn YES;}}if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN){// ... but WWAN connections are OK if the calling application//     is using the CFNetwork (CFSocketStream?) APIs.return YES;}}}return NO;
}

而且它已为您测试了iOS 5 。


#31楼

iOS 5的可达性版本是darkseed / Reachability.h 。 不是我的! =)

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

  1. 如何在 iOS、MacOS 上使用 ChatGPT 和适用于 iPhone 的最佳 ChatGPT 应用程序

    目录 什么是聊天 GPT? 如何在我的 iPhone 上使用 ChatGPT? 适用于 iPhone 的最佳 ChatGPT 应用程序 在过去的几周里,出现了许多 ChatGPT 应用程序和网站.如果 ...

  2. [ R ] 如何在iPadOS、iOS和MacOS上优雅的跑R —— 使用腾讯云搭建RStudio server的懒人包

    引言 如何在iPadOS/iOS/MacOS等多个平台优雅的连贯的高效的跑R?这是一个有关于使用腾讯云搭建RStudio Server的懒人包 Outline: What: 什么是RStudio Se ...

  3. linux刻录windows光盘启动,如何在 Windows / Ubuntu / macOS 上刻录 Ubuntu 启动光盘

    Linux 从入门到放弃,第一篇,必须是安装.正好实验室的服务器也需要重装一下,今天就记录一下如何在 Windows / Ubuntu / macOS 上制作 Ubuntu 的启动光盘.制作启动U盘不 ...

  4. macos上的ios虚拟机_如何将中级帖子转换为可在iOS和macOS上运行的SwiftUI应用

    macos上的ios虚拟机 I recently turned one of my posts into a SwiftUI app, and the process is very easy. My ...

  5. macos 查找文件_如何在Windows和macOS上查找和安装颜色配置文件以获取更准确的显示器...

    macos 查找文件 Color profiles, also known as ICC or ICM files, contain a collection of settings that hel ...

  6. swift 如何在IOS应用图标上添加消息数

    在应用图标右上角添加消息数提醒,可以很方便的告知用户该应用中有无新消息需要处理.下面用xcode 7.3.1来简要说明一下如何用swift语言进行此功能的实现. 1.修改 AppDelegate.sw ...

  7. 1解决“下载软件仓库信息失败,检查您的internet连接“问题

    软件源有问题 不是网络有问题备份原有的源sudo cp /etc/apt/sources.list /etc/apt/sources.list.copy 打开 sudo gedit /etc/apt/ ...

  8. Macos上的专业加密通讯工具,十分安全。使用了信号协议,该协议结合了预密钥,Double Ratchet算法和3-DH握手信号。

    想要让自己聊天信息变得更加安全有隐秘性吗?Signal Desktop for Mac版是一款Macos上的专业加密通讯工具,十分安全.使用了信号协议,该协议结合了预密钥,Double Ratchet ...

  9. Apple 为 iOS 和 macOS 更新了 iWork 的新链接功能等

    Apple 更新了其 iWork 应用程序套件,包括适用于 iOS 和 macOS 的 Pages.Keynotes 和 Numbers,增加了与"课业"相关的新功能,以及将网页. ...

最新文章

  1. 储存卡怎么格式化为fat32_电脑复制文件到U盘提示文件容量太大该怎么办?
  2. Java中的引用与C中的指针
  3. [pymongo] pymongo.errors.CursorNotFound Exception
  4. 机器学习:决策树过拟合与剪枝,决策树代码实现(三)
  5. oracle / parallle /,Oracle海量数据迁移之使用shell启用多个动态并行
  6. 05 Python - Python运行
  7. NoSQL 是否可以用来做日志中心 ?
  8. C#.NET中的事件2
  9. 在react中使用定时器
  10. vba判断文件是否存在的两种方法
  11. 10.2829(NOIP模拟修正总结)
  12. 上大学有用吗?35岁以上的程序员都去哪里了
  13. win10安装misql8_Windows10下安装MySQL8.0
  14. 无人编辑,人工智能编辑,AI编辑机器人-资讯频道编辑
  15. 注册表系列之恶作剧之吻
  16. 自由移动的气泡_MBBR工艺—移动床生物膜反应器
  17. 医院信息化服务器配置,医院信息化建设方案(完整).doc
  18. 【14】婚礼片剪辑案例【15】电视剧片头剪辑案例
  19. 【Java基础】2020如何查看Java官方文档
  20. 多个精美的导航样式web2.0源码

热门文章

  1. Android String.xml 批量翻译工具 | Android string.xml 各国语言转换
  2. 面试常问 Java基础 冒泡排序
  3. 【剑指offer-Java版】04替换空格
  4. springcloud上传文件_Spring Cloud实战:服务链路追踪Spring Cloud Sleuth
  5. webpack自动打包功能配置
  6. CF1038D Slime 构造
  7. jenkins如何实现重新发布历史构建记录里的版本
  8. 2014年百度之星资格赛第一题Energy Conversion
  9. Centos7 安装Mini后相关配置
  10. 计算机网络系统--Microsoft Lync 与 腾讯通RTX 对比(转载)