如何检查活动上的互联网连接iOS或mac os?
-
23-08-2019 - |
题
我想检查,看看如果我有一个互联网连接在使用的 可可触摸 图书馆或在mac os使用 可可 库。
我想出了一个方式做到这一使用一个 NSURL
.我做的方式似乎有点不可靠的(因为即使是谷歌一天以下,并依赖第三方似乎坏),并同时我可以检查看的响应,从其他一些网站,如果谷歌没作出回应,这似乎浪费和不必要的开销对我的应用程序。
- (BOOL) connectedToInternet
{
NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
return ( URLString != NULL ) ? YES : NO;
}
是我做了什么坏,(更不要提 stringWithContentsOfURL
使用iOS3.0和mac os10.4)和如果是的话,什么是更好的方式来做到这一点?
解决方案
重要提示:此检查应的总是的异步执行。大多数的答案如下同步,所以要小心,否则会冻结您的应用程序。
夫特
1)通过的CocoaPods或迦太基安装: https://github.com/ashleymills/Reachability.swift
2)通过封闭件的可达性测试
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
1)SystemConfiguration
框架添加到项目中,但不用担心,包括它的任何地方。
2)添加托尼百万的版本Reachability.h
和Reachability.m
到项目(在这里找到: https://github.com / tonymillion /可达性)
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 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];
}
重要提示:的Reachability
类是最常用的类别中的一个项目,所以你可能会遇到的命名与其他项目冲突。如果发生这种情况,你必须重新命名对Reachability.h
和Reachability.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
}
此方法不会以这样的东西等待改变网络状态。它只是测试状态,当你要求它。
,我创建了一个会正确地检查这个,您无需包括任何类的功能。
在项目中包含的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* 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,而是一部分 这个苹果公司的样品申请.刚刚下载,并复制的可达性。h/m到项目中。还有,你必须添加系统配置的框架项目。
下面是一个非常简单的答案:
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应该指向一个非常小的网站。我在这里使用谷歌的移动网站,但如果我有一个可靠的web服务器我上传的小文件只有一个字符在它作为最大速度。
如果检查设备是否是不知何故的连接到互联网,你想要做的一切,我肯定会推荐使用这种简单的解决方案。如果您需要了解用户是如何连接的,使用可达性是要走的路。
小心:这将阻止简要你的线程,同时它加载的网站。就我而言,这不是一个问题,但你应该考虑这个(学分布拉德指出这一点)。
下面是我怎么做我的应用程序:当一个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
}
}];
}
苹果供给示例代码以检查不同类型的网络的可用性。可选地有一个例如在iPhone开发的食谱。
注意:请参阅@这个回答关于使用苹果的可达性代码KHG的评论
您可以通过使用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.
苹果提供一个示例应用程序,其不正是这样:
只有可达性类已被更新。您现在可以使用:
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");}
为iOS 5上可联系性的版本是 darkseed / Reachability.h 。不是我的! =)
有一个非常漂亮的,ARC-和GCD-使用可达性的现代化在这里:
如果你使用 AFNetworking
你可以使用其自己的执行网络可达性的状态。
最好的方式来使用 AFNetworking
是的子类 AFHTTPClient
类和使用此类做你的网络连接。
一个优点是使用这种方法是,可以使用 blocks
设置所需要的行为时可达性状态的变化。假设,我已经创建了一个单独的子 AFHTTPClient
(作为上述关于"子类注意到"上 AFNetworking文档)命名的 BKHTTPClient
, 我会做这样的事情:
BKHTTPClient *httpClient = [BKHTTPClient sharedClient];
[httpClient setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
{
if (status == AFNetworkReachabilityStatusNotReachable)
{
// Not reachable
}
else
{
// Reachable
}
}];
你也可以检查有无线网络或WLAN连接的具体的使用 AFNetworkReachabilityStatusReachableViaWWAN
和 AFNetworkReachabilityStatusReachableViaWiFi
枚举(更多的在这里).
我已经使用的代码中 这次讨论, 看来工作的现(阅读 整个 线!).
我还没有详尽的测试,它与每一种可以想象一种连接(如同特设Wi-Fi)。
非常简单。...试试这些步骤:
步骤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");
}
}
-(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;
}
}
- (void)viewWillAppear:(BOOL)animated
{
NSString *URL = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
return (URL != NULL ) ? YES : NO;
}
或者使用的可达性类强>
有两种方法来检查使用iPhone SDK互联网的可用性:
<强> 1。检查谷歌网页是否打开。
<强> 2。可达性类强>
有关的更多信息,请参阅 可达性 (苹果开发)。
使用 http://huytd.github.io/datatify/ 。这比自己添加库和写代码更容易。
<强>第一强>:添加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");
}
}
首先下载可达类,并把reachability.h和reachabilty.m文件在的Xcode
最好的办法就是让常用功能类(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;
}
现在可以通过调用此类方法检查在任何类的网络连接。
还有使用iPhone SDK来检查因特网连接的另一种方法。
尝试以实现用于所述网络连接以下代码。
#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;
}
我发现很简单和易于使用的图书馆 SimplePingHelper.
样本代码: chrishulbert/SimplePingHelper (想)
下载的可达性文件, https://gist.github.com/darkseed/1182373
和add
CFNetwork.framework
和'系统配置.框架'的框架做#进口"可达性。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");
}
}
在可达性类的是确定以找出是否Internet连接可用的设备或不...
但是,在访问一个 Intranet资源的情况下:
与所述可达性类总是返回true执行ping内网服务器。
因此,在这种情况下一个快速的解决方案是创建与服务等的webMethods沿着一个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检查我的内网资源的可达性。
要做到这一点你自己是非常简单的。下面的方法会奏效。只要确保不允许主机名的协议,如HTTP,HTTPS等与名字传递英寸
-(BOOL)hasInternetConnection:(NSString*)urlAddress
{
SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [urlAddress UTF8String]);
SCNetworkReachabilityFlags flags;
if (!SCNetworkReachabilityGetFlags(ref, &flags))
{
return NO;
}
return flags & kSCNetworkReachabilityFlagsReachable;
}
它是快速简单和无痛的。
除了可达您也可以使用简单的ping助手库。它的工作原理非常好的和简单集成。
我觉得这个是最好的答案。
“是” 意味着连接。 “否” 表示断开。
#import "Reachability.h"
- (BOOL)canAccessInternet
{
Reachability *IsReachable = [Reachability reachabilityForInternetConnection];
NetworkStatus internetStats = [IsReachable currentReachabilityStatus];
if (internetStats == NotReachable)
{
return NO;
}
else
{
return YES;
}
}
在您的Reachable.h
进口ViewController
类,并使用下面的代码来检查的连接
#define hasInternetConnection [[Reachability reachabilityForInternetConnection] isReachable]
if (hasInternetConnection){
// To-do block
}
- 步骤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"); }
<强>检查在(IOS)的Xcode 8因特网连接可用性,夫特3.0 强>
这是对像我们的设备被连接到的任何网络或不检查网络可用性简单方法。我设法将其翻译为雨燕3.0,这里的最终代码。现有的苹果可达类和其他第三方库似乎太复杂翻译斯威夫特。
此既适用于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")
}