提问人:Brock Woolf 提问时间:7/5/2009 最后编辑:ArasuvelBrock Woolf 更新时间:2/7/2023 访问量:508736
如何在 iOS 或 macOS 上检查活动的 Internet 连接?
How can I check for an active Internet connection on iOS or macOS?
问:
我想检查一下我在使用 Cocoa Touch 库的 iOS 上或使用 Cocoa 库的 macOS 上是否有 Internet 连接。
我想出了一种使用 .我这样做的方式似乎有点不可靠(因为即使是谷歌有一天也可能倒闭,依赖第三方似乎很糟糕),虽然如果谷歌没有回应,我可以检查其他一些网站的回复,但这似乎很浪费,而且对我的应用程序造成了不必要的开销。NSURL
- (BOOL)connectedToInternet {
NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
return ( URLString != NULL ) ? YES : NO;
}
我做得不好吗(更不用说在 iOS 3.0 和 macOS 10.4 中被弃用),如果是这样,还有什么更好的方法可以做到这一点?stringWithContentsOfURL
答:
Apple 提供了一个示例应用,它完全可以做到这一点:
评论
Apple 提供了示例代码来检查不同类型的网络可用性。另外,iPhone 开发人员食谱中有一个示例。
注意:请参阅@KHG对此答案中关于使用 Apple 可访问性代码的评论。
评论
这曾经是正确的答案,但现在已经过时了,因为您应该订阅可访问性通知。此方法同步检查:
您可以使用 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) { }
Reachability 类不随 SDK 一起提供,而是此 Apple 示例应用程序的一部分。只需下载它,并将 Reachability.h/m 复制到您的项目中。此外,还必须将 SystemConfiguration 框架添加到项目中。
评论
仅更新了 Reachability 类。您现在可以使用:
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");}
评论
重要提示:此检查应始终异步执行。下面的大多数答案都是同步的,所以要小心,否则你会冻结你的应用程序。
迅速
通过 CocoaPods 或 Carthage 安装:https://github.com/ashleymills/Reachability.swift
通过闭包测试可达性
let reachability = Reachability()! reachability.whenReachable = { reachability in if reachability.connection == .wifi { print("Reachable via WiFi") } else { print("Reachable via Cellular") } } reachability.whenUnreachable = { _ in print("Not reachable") } do { try reachability.startNotifier() } catch { print("Unable to start notifier") }
Objective-C语言
将框架添加到项目中,但不要担心将其包含在任何地方
SystemConfiguration
将 Tony Million 的 和 版本添加到项目中(可在此处找到:https://github.com/tonymillion/Reachability
Reachability.h
Reachability.m
)更新接口部分
#import "Reachability.h" // Add this to the interface in the .m file of your view controller @interface MyViewController () { Reachability *internetReachableFoo; } @end
然后在视图控制器的 .m 文件中实现此方法,您可以调用该方法
// Checks if we have an internet connection or not - (void)testInternetConnection { internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"]; // Internet is reachable internetReachableFoo.reachableBlock = ^(Reachability*reach) { // Update the UI on the main thread dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"Yayyy, we have the interwebs!"); }); }; // Internet is not reachable internetReachableFoo.unreachableBlock = ^(Reachability*reach) { // Update the UI on the main thread dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"Someone broke the internet :("); }); }; [internetReachableFoo startNotifier]; }
重要提示:该类是项目中最常用的类之一,因此可能会遇到与其他项目的命名冲突。如果发生这种情况,您必须将其中一对 and 文件重命名为其他名称才能解决问题。Reachability
Reachability.h
Reachability.m
注意:您使用的域无关紧要。它只是测试任何域的网关。
评论
SystemConfiguration.framework
我喜欢让事情变得简单。我这样做的方法是:
//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 的 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 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;
}
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;
}
}
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 测试。
评论
您可以通过 使用(可在此处获得)。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.
评论
这是一个非常简单的答案:
NSURL *scriptUrl = [NSURL URLWithString:@"http://www.google.com/m"];
NSData *data = [NSData dataWithContentsOfURL:scriptUrl];
if (data)
NSLog(@"Device is connected to the Internet");
else
NSLog(@"Device is not connected to the Internet");
该 URL 应指向一个非常小的网站。我在这里使用谷歌的移动网站,但如果我有可靠的网络服务器,我会上传一个小文件,里面只有一个字符,以获得最大速度。
如果检查设备是否以某种方式连接到互联网是您想要做的一切,我绝对建议您使用这个简单的解决方案。如果您需要了解用户是如何连接的,那么使用可访问性是要走的路。
小心:这将在加载网站时短暂阻止您的线程。就我而言,这不是问题,但你应该考虑这一点(感谢布拉德指出这一点)。
评论
- (void)viewWillAppear:(BOOL)animated
{
NSString *URL = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
return (URL != NULL ) ? YES : NO;
}
或者使用 Reachability 类。
有两种方法可以使用 iPhone SDK 检查互联网可用性:
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.ReloadIgnoringLocalAndRemoteCacheData
request.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:headRequest
completionHandler:^(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
}
}];
}
评论
如果您使用的是 AFNetworking
,则可以使用其自己的实现来获取 Internet 可访问性状态。
最好的使用方法是将类子类化,并使用此类进行网络连接。AFNetworking
AFHTTPClient
使用此方法的优点之一是,当可访问性状态更改时,可以使用此方法设置所需的行为。假设我已经创建了一个名为 的单例子类(如 AFNetworking 文档上的“子类注释”中所述),我会做这样的事情:blocks
AFHTTPClient
BKHTTPClient
BKHTTPClient *httpClient = [BKHTTPClient sharedClient];
[httpClient setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
{
if (status == AFNetworkReachabilityStatusNotReachable)
{
// Not reachable
}
else
{
// Reachable
}
}];
您还可以专门使用 和 枚举检查 Wi-Fi 或 WLAN 连接(更多内容在这里)。AFNetworkReachabilityStatusReachableViaWWAN
AFNetworkReachabilityStatusReachableViaWiFi
-(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;
}
}
评论
首先下载 reachability 类,并将 reachability.h 和 reachabilty.m 文件放入 Xcode 中。
最好的方法是创建一个通用的 Functions 类 (NSObject),以便您可以在任何类中使用它。以下是网络连接可访问性检查的两种方法:
+(BOOL) reachabiltyCheck
{
NSLog(@"reachabiltyCheck");
BOOL status =YES;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object: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 addy
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
// Recover reachability flags
SCNetworkReachabilityRef 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;
}
现在,您可以通过调用此类方法检查任何类中的网络连接。
Reachability 类可以确定 Internet 连接是否可用于设备...
但是,在访问 Intranet 资源的情况下:
使用 reachability 类对 Intranet 服务器执行 ping 操作始终返回 true。
因此,在此方案中,一个快速的解决方案是创建一个 Web 方法,该方法与服务上的其他 Web 方法一起调用。
应该返回一些东西。pingme
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:urlReq
returningResponse:&response
error:&error];
NSLog(@"receivedData:%@",receivedData);
if (receivedData !=nil)
{
return YES;
}
else
{
NSLog(@"Data is null");
return NO;
}
}
上述方法对我来说非常有用,因此每当我尝试向服务器发送一些数据时,我总是使用这个低超时 URLRequest 检查我的 Intranet 资源的可访问性。
从 https://github.com/tonymillion/Reachability 获取 Reachabilty 类,在项目中添加系统配置框架,在类中导入 Reachability.h 并实现自定义方法,如下所示:
- (BOOL)isConnectedToInternet
{
//return NO; // Force for offline testing
Reachability *hostReach = [Reachability reachabilityForInternetConnection];
NetworkStatus netStatus = [hostReach currentReachabilityStatus];
return !(netStatus == NotReachable);
}
评论
return [[Reachability reachabilityForInternetConnection] isReachable];
在 中导入类,并使用以下代码检查连通性:Reachable.h
ViewController
#define hasInternetConnection [[Reachability reachabilityForInternetConnection] isReachable]
if (hasInternetConnection){
// To-do block
}
评论
还有另一种使用 iPhone SDK 检查 Internet 连接的方法。
尝试为网络连接实现以下代码。
#import <SystemConfiguration/SystemConfiguration.h>
#include <netdb.h>
/**
Checking for network availability. It returns
YES if the network is available.
*/
+ (BOOL) connectedToNetwork
{
// Create zero addy
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
// Recover reachability flags
SCNetworkReachabilityRef 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;
}
它快速、简单且无痛。
第一:在框架中添加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 work
UIAlertView *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; }
类型 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");
}
}
评论
导入 “Reachability.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;
}
}
并在框架中添加和“SystemConfiguration.framework”
CFNetwork.framework
#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 work
UIAlertView *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 步:在项目中添加 Reachability 类。
- 步骤 2:导入 Reachability 类
第 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"); }
评论
在 (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 = 0
if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
return false
}
let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
let 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 和异步。大多数答案是同步解决方案,如果您的连接速度非常慢,它将阻止您的主线程。
这个解决方案更好,但并不完美,因为它依靠 Google 来检查连接性,因此请随意使用另一个 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 = .reloadIgnoringLocalAndRemoteCacheData
request.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];
}
评论
斯威夫特 3 / 斯威夫特 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 in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}
var flags = SCNetworkReachabilityFlags()
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
return false
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
}
评论
阿拉莫火
我知道这个问题是要求 Coca Touch 解决方案,但我想为在 iOS 上搜索检查 Internet 连接的人提供一个解决方案,并且在这里还有一个选择。
如果您已经在使用 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 = false
private func listenForReachability() {
self.manager?.listener = { [unowned self] status in
switch status {
case .notReachable:
self.reachable = false
case .reachable(_), .unknown:
self.reachable = true
}
}
self.manager?.startListening()
}
func isConnected() -> Bool {
return reachable
}
}
这是一个单例类。每次,当用户连接或断开网络时,它都会正确地覆盖到 true/false,因为我们开始监听 on 单例初始化。self.reachable
NetworkReachabilityManager
此外,为了监视可访问性,您需要提供主机。目前,我正在使用 google.com,但如果需要,请随时更改为任何其他主机或您的主机之一。将类名和文件名更改为与项目匹配的任何名称。
使用 Xcode 9 和 Swift 4.0 在 (iOS) 中检查 Internet 连接可用性
请按照以下步骤操作
步骤1:
创建一个扩展文件,并将其命名为 ReachabilityManager.swift。然后添加下面的代码行。
import Foundation
import SystemConfiguration
public 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
}
对于我的 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 in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}
var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
let ret = (isReachable && !needsConnection)
return ret
}
}
使用条件语句,
if Reachability.isConnectedToNetwork() {
// Enter your code here
}
}
else {
print("NO Internet connection")
}
此类在应用使用 Internet 连接的几乎所有情况下都很有用。 例如,如果条件为真,则可以调用 API 或执行任务。
评论
请试试这个。它会帮助你 (Swift 4)
通过 CocoaPods 或 Carthage 安装 Reachability:可访问性
导入 Reachability 并在 Network 类中使用它
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! Reachability if reachability.connection != .none { self.isReachable = true } else { self.isReachable = false } print("Internet Connected : \(self.isReachable)") //Print Status of Network Connection } }
在您需要的地方使用如下。
var networkOBJ = Network() // Use "networkOBJ.isReachable" for Network Status print(networkOBJ.isReachable)
//
// Connectivity.swift
//
//
// Created by Kausik Jati on 17/07/20.
//
//
import Foundation
import 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? = nil
private let queue = DispatchQueue.global(qos: .background)
private var isLowDataMode = false
static let instance = Connectivity()
private override init() {
super.init()
monitor.start(queue: queue)
startMonitorNetwork()
}
private func startMonitorNetwork() {
monitor.pathUpdateHandler = { path in
if #available(iOS 13.0, *) {
self.isLowDataMode = path.isConstrained
} else {
// Fallback on earlier versions
self.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 reference
var alamofireSessionManager: Session!
func checkHostReachable(completionHandler: @escaping (_ isReachable:Bool) -> Void) {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 1
configuration.timeoutIntervalForResource = 1
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
alamofireSessionManager = Session(configuration: configuration)
alamofireSessionManager.request("https://google.com").response { response in
completionHandler(response.response?.statusCode == 200)
}
}
// Using
checkHostReachable() { (isReachable) in
print("isReachable:\(isReachable)")
}
使用 iOS 12 或 macOS v10.14 (Mojave) 或更高版本时,您可以使用代替史前类。作为奖励,您可以轻松检测当前的网络连接类型:NWPathMonitor
Reachability
import Network // Put this on top of your class
let monitor = NWPathMonitor()
monitor.pathUpdateHandler = { path in
if 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
评论
path.usesInterfaceType(.loopback)
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
}
评论
return (BOOL)URLString;
return !!URLString
return URLString != nil
NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"https://twitter.com/getibox"] encoding:NSUTF8StringEncoding error:nil];