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

我想检查一下我是否在使用CocoaTouch库的iOS或使用可可库的macOS上有Internet连接。

我想出了一个方法来做到这一点使用NSURL.我这样做的方式似乎有点不可靠(因为即使谷歌有一天可能会关闭,依赖第三方似乎不好),虽然我可以检查,看看从其他一些网站的回应,如果谷歌没有回应,这似乎是浪费和不必要的开销在我的应用程序。

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

我做的不好(更不用说stringWithContentsOfURL在iOS3.0和macOS 10.4中已被弃用),如果是这样,有什么更好的方法来实现这一点?

500273 次浏览

Apple提供了一个示例应用程序,它完全是这样做的:

可达性

Apple提供示例代码来检查不同类型的网络可用性。或者在iPhone开发人员食谱中有一个示例

备注:请参阅@KHG对有关使用Apple可达性代码的答案的评论。

我使用了这次讨论中的代码,它似乎工作正常(阅读整个线程!)。

我还没有对每一种可能的连接(如特设Wi-Fi)进行详尽的测试。

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


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

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

可达性类不是SDK附带的,而是此Apple示例应用程序的一部分。只需下载它,并将Reachaability. h/m复制到您的项目中。此外,您必须将SystemConfiguration框架添加到您的项目中。

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

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

重要:此检查应该总是异步执行。下面的大多数答案都是同步的,所以要小心,否则你会冻结你的应用程序。


Swift

  1. 通过CocoaPods或Carthage安装: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")}

Objective-c

  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文件对中的一个重命名为其他文件来解决问题。

备注:您使用的域并不重要。它只是测试任何域的网关。

我喜欢把事情简单化。我的做法是:

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

此方法不会等待更改的网络状态来执行操作。它只是在您要求时测试状态。

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

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

这是iOS5测试。

iOS5的可达性版本是黑暗种子/恢复. h。这不是我的!=)

这里有一个漂亮的,使用ARC和GCD的可达性现代化:

可达性

您可以使用Reachability by(此处提供)。

#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.

这里有一个非常简单的答案:

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

URL应该指向一个非常小的网站。我在这里使用谷歌的移动网站,但如果我有一个可靠的网络服务器,我会上传一个只有一个字符的小文件以获得最大速度。

如果检查设备是否不知何故连接到Internet是您想要做的一切,我绝对建议使用这个简单的解决方案。如果您需要知道用户是如何连接的,使用可达性是最好的选择。

小心:这将在加载网站时短暂阻止您的线程。在我的情况下,这不是问题,但您应该考虑这一点(布拉德指出了这一点)。

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

或者使用可达性类

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

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

2.可达性类

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

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

Swift代码

func checkInternet(flag:Bool, completionHandler:(internet:Bool) -> Void){UIApplication.sharedApplication().networkActivityIndicatorVisible = true
let url = NSURL(string: "http://www.google.com/")let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "HEAD"request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheDatarequest.timeoutInterval = 10.0
NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue.mainQueue(), completionHandler:{(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
let rsp = response as! NSHTTPURLResponse?
completionHandler(internet:rsp?.statusCode == 200)})}
func yourMethod(){self.checkInternet(false, completionHandler:{(internet:Bool) -> Void in
if (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}}];}

如果您使用的是#0,您可以使用它自己的实现来获取Internet可达性状态。

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

使用这种方法的优点之一是,当可达性状态发生变化时,你可以使用blocks来设置所需的行为。假设我创建了AFHTTPClient的单例子类(如AFNetworkdocs上的“子类注释”所述)名为BKHTTPClient,我会做如下操作:

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

您还可以专门使用AFNetworkReachabilityStatusReachableViaWWANAFNetworkReachabilityStatusReachableViaWiFi枚举(这里更多)检查Wi-Fi或WLAN连接。

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

首先下载可达性类,并将reac的. h和reac的. m文件放在您的Xcode中。

最好的方法是创建一个通用的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;}

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

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

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

使用可达性类ping Intranet服务器始终返回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资源的可达性。

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

https://github.com/tonymillion/Reachability获取Reac的类,在你的项目中添加系统配置框架,在你的类中导入Reac的. h并实现自定义方法如下:

- (BOOL)isConnectedToInternet{//return NO; // Force for offline testingReachability *hostReach = [Reachability reachabilityForInternetConnection];NetworkStatus netStatus = [hostReach currentReachabilityStatus];return !(netStatus == NotReachable);}

ViewController中导入Reachable.h类,并使用以下代码检查连通性

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

还有另一种使用iPhoneSDK检查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;}

自己执行此操作非常简单。以下方法将起作用。只是确保不允许主机名协议(如HTTP、HTTPS等)与名称一起传递。

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

它是快速简单和无痛的。

我发现它简单易用库Simpleping帮助器

示例代码:Chris hul bert/简单的ping助手github

除了可达性之外,您还可以使用简单的ping助手库。它工作得非常好,易于集成。

第一:在框架中添加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");}}

非常简单……尝试以下步骤:

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

  • Type 2:

    Import header : #import "Reachability.h"

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

Step 4: How to use:

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

导入“康复. h”

-(BOOL)netStat{Reachability *test = [Reachability reachabilityForInternetConnection];return [test isReachable];}

我认为这是最好的答案。

“是”意味着连接。“否”意味着断开连接。

#import "Reachability.h"
- (BOOL)canAccessInternet{Reachability *IsReachable = [Reachability reachabilityForInternetConnection];NetworkStatus internetStats = [IsReachable currentReachabilityStatus];
if (internetStats == NotReachable){return NO;}else{return YES;}}
  1. 下载可达性文件,https://gist.github.com/darkseed/1182373

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

  3. #导入“康复. 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");}}

创建AFNetworkReachabilityManager对象并使用以下代码跟踪网络连接

self.reachabilityManager = [AFNetworkReachabilityManager managerForDomain:@"yourDomain"];[self.reachabilityManager startMonitoring];[self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {switch (status) {case AFNetworkReachabilityStatusReachableViaWWAN:case AFNetworkReachabilityStatusReachableViaWiFi:break;case AFNetworkReachabilityStatusNotReachable:break;default:break;}}];
  • 第1步:在Project中添加Reachaability类。
  • 第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;}}}
  • Step 4: Call the function as below:

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

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

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

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

不要忘记将“SystemConfiguration.framework”添加到您的项目生成器。

//Create new swift class file Reachability in your project.import SystemConfigurationpublic 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)) != 0
return 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")}

这是针对Swift 3.0和async的。大多数答案都是同步解决方案,如果您的连接非常慢,它会阻塞您的主线程。

这个解决方案更好,但并不完美,因为它依赖于谷歌来检查连接,所以请随意使用另一个URL。

func checkInternetConnection(completionHandler:@escaping (Bool) -> Void){if let url = URL(string: "http://www.google.com/"){var request = URLRequest(url: url)request.httpMethod = "HEAD"request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheDatarequest.timeoutInterval = 5
let tast = URLSession.shared.dataTask(with: request, completionHandler:{(data, response, error) in
completionHandler(error == nil)})tast.resume()}else{completionHandler(true)}}

试试这个:

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

if ([self.delegate respondsToSelector:@selector(getErrorResponse:)]) {[self.delegate performSelector:@selector(getErrorResponse:) withObject:@"No Network Connection"];}
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"BMC" message:@"No Network Connection" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK",nil];[alertView show];

}

Swift 3/Swift 4

您必须先导入

import SystemConfiguration

您可以使用以下方法检查Internet连接:

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

alamofire

我知道这个问题是问可口可乐触摸解决方案,但我想提供一个解决方案的人谁搜索检查互联网连接iOS,并将有一个更多的选择在这里。

如果您已经在使用alamofire,那么您可以从中受益。

您可以将以下类添加到您的应用程序中,并调用MNNetworkUtils.main.isConnected()以获取有关它是否已连接的布尔值。

#import Alamofire
class MNNetworkUtils {static let main = MNNetworkUtils()init() {manager = NetworkReachabilityManager(host: "google.com")listenForReachability()}
private let manager: NetworkReachabilityManager?private var reachable: Bool = falseprivate func listenForReachability() {self.manager?.listener = { [unowned self] status inswitch status {case .notReachable:self.reachable = falsecase .reachable(_), .unknown:self.reachable = true}}self.manager?.startListening()}
func isConnected() -> Bool {return reachable}}

这是一个单例类。每次,当用户连接或断开网络时,它都会正确地将self.reachable覆盖为true/false,因为我们开始在单例初始化时监听NetworkReachabilityManager

此外,为了监控可达性,您需要提供一个主机。目前,我正在使用google.com,但如果需要,请随时更改为任何其他主机或您的主机。将类名和文件名更改为与您的项目匹配的任何名称。

使用Xcode 9和Swift 4.0检查(iOS)中的Internet连接可用性

按照以下步骤操作

步骤1:

创建一个扩展文件并将其命名为ReachabilityManager.swift。然后添加下面的代码行。

import Foundationimport SystemConfigurationpublic class ConnectionCheck{class func isConnectedToNetwork() -> Bool{var zeroAddress = sockaddr_in()zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress,{$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {SCNetworkReachabilityCreateWithAddress(nil, $0)}})else {return false}
var flags: SCNetworkReachabilityFlags = []if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {return false}
let isReachable = flags.contains(.reachable)let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)}}

步骤2:使用下面的代码调用上面的扩展。

if ConnectionCheck.isConnectedToNetwork(){print("Connected")// Online related Business logic}else{print("disConnected")// Offline related business logic}
Pod `Alamofire` has `NetworkReachabilityManager`, you just have to create one function
func isConnectedToInternet() ->Bool {return NetworkReachabilityManager()!.isReachable}

介绍Network.framework:Socket的现代替代方案

我们应该在某个时候摆脱可达性。

对于我的iOS项目,我建议使用

可达性类

在Swift中声明。对我来说,它可以很好地与

Wi-Fi和蜂窝数据

import SystemConfiguration
public class Reachability {
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(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 = SCNetworkReachabilityFlags(rawValue: 0)if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {return false}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0let ret = (isReachable && !needsConnection)return ret}}

使用条件语句,

if Reachability.isConnectedToNetwork() {// Enter your code here}}else {print("NO Internet connection")}

此类几乎在您的应用程序使用Internet连接的所有情况下都很有用。例如,如果条件为真,则可以调用API或执行任务。

请尝试这个。它会帮助你(Swift 4)

  1. 通过CocoaPods或Carthage安装可达性可达性

  2. 导入可达性并在网络类中使用它

    import Reachability
    class Network {
    private let internetReachability : Reachability?var isReachable : Bool = false
    init() {
    self.internetReachability = Reachability.init()do{try self.internetReachability?.startNotifier()NotificationCenter.default.addObserver(self, selector: #selector(self.handleNetworkChange), name: .reachabilityChanged, object: internetReachability)}catch {print("could not start reachability notifier")}}
    @objc private func handleNetworkChange(notify: Notification) {
    let reachability = notify.object as! Reachabilityif reachability.connection != .none {self.isReachable = true}else {self.isReachable = false}print("Internet Connected : \(self.isReachable)") //Print Status of Network Connection}}
  3. 在你需要的地方像下面这样使用。

    var networkOBJ = Network()// Use "networkOBJ.isReachable" for Network Statusprint(networkOBJ.isReachable)
////  Connectivity.swift//////  Created by Kausik Jati on 17/07/20.////
import Foundationimport Network
enum ConnectionState: String {case notConnected = "Internet connection not avalable"case connected = "Internet connection avalable"case slowConnection = "Internet connection poor"}protocol ConnectivityDelegate: class {func checkInternetConnection(_ state: ConnectionState, isLowDataMode: Bool)}class Connectivity: NSObject {private let monitor = NWPathMonitor()weak var delegate: ConnectivityDelegate? = nilprivate let queue = DispatchQueue.global(qos: .background)private var isLowDataMode = falsestatic let instance = Connectivity()private override init() {super.init()monitor.start(queue: queue)startMonitorNetwork()}private func startMonitorNetwork() {monitor.pathUpdateHandler = { path inif #available(iOS 13.0, *) {self.isLowDataMode = path.isConstrained} else {// Fallback on earlier versionsself.isLowDataMode = false}        
if path.status == .requiresConnection {print("requiresConnection")self.delegate?.checkInternetConnection(.slowConnection, isLowDataMode: self.isLowDataMode)} else if path.status == .satisfied {print("satisfied")self.delegate?.checkInternetConnection(.connected, isLowDataMode: self.isLowDataMode)} else if path.status == .unsatisfied {print("unsatisfied")self.delegate?.checkInternetConnection(.notConnected, isLowDataMode: self.isLowDataMode)}}    
}func stopMonitorNetwork() {monitor.cancel()}}

Swift 5, Alamofire,主机

// Session referencevar alamofireSessionManager: Session!
func checkHostReachable(completionHandler: @escaping (_ isReachable:Bool) -> Void) {let configuration = URLSessionConfiguration.defaultconfiguration.timeoutIntervalForRequest = 1configuration.timeoutIntervalForResource = 1configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
alamofireSessionManager = Session(configuration: configuration)
alamofireSessionManager.request("https://google.com").response { response incompletionHandler(response.response?.statusCode == 200)}}
// UsingcheckHostReachable() { (isReachable) inprint("isReachable:\(isReachable)")}

使用iOS12或macOS v10.14(Mojave)或更高版本时,您可以使用NWPathMonitor而不是历史前的Reachability类。作为奖励,您可以轻松检测当前的网络连接类型:

import Network // Put this on top of your class
let monitor = NWPathMonitor()
monitor.pathUpdateHandler = { path inif path.status != .satisfied {// Not connected}else if path.usesInterfaceType(.cellular) {// Cellular 3/4/5g connection}else if path.usesInterfaceType(.wifi) {// Wi-Fi connection}else if path.usesInterfaceType(.wiredEthernet) {// Ethernet connection}}
monitor.start(queue: DispatchQueue.global(qos: .background))

更多信息:https://developer.apple.com/documentation/network/nwpathmonitor

Swift 5及以后:

public class Reachability {class func isConnectedToNetwork() -> Bool {var zeroAddress = sockaddr_in()zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {SCNetworkReachabilityCreateWithAddress(nil, $0)}}) else {return false}
var flags: SCNetworkReachabilityFlags = []if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {return false}
let isReachable = flags.contains(.reachable)let needsConnection = flags.contains(.connectionRequired)
return (isReachable && !needsConnection)}

像这样调用这个类:

if Reachability.isConnectedToNetwork() == true {// Do something} else {// Do something}