Bro*_*olf 1309 macos cocoa cocoa-touch reachability ios
我想查看我是否在iOS上使用Cocoa Touch库或使用Cocoa库在macOS 上建立了Internet连接.
我想出了一个方法,使用一个NSURL.我这样做的方式似乎有点不可靠(因为即使谷歌有一天会失败并依赖第三方看起来很糟糕),而且如果谷歌没有回应,我可以查看其他网站的回复,在我的应用程序中看起来似乎很浪费并且不必要的开销
- (BOOL) connectedToInternet
{
NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
return ( URLString != NULL ) ? YES : NO;
}
Run Code Online (Sandbox Code Playgroud)
我做得不好,(更不用说stringWithContentsOfURL在iOS 3.0和macOS 10.4中被弃用)如果是这样,有什么更好的方法来实现这一目标?
iwa*_*bed 1272
重要说明:此检查应始终异步执行.下面的大部分答案都是同步的,所以要小心,否则你会冻结你的应用程序.
1)通过CocoaPods或Carthage安装: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")
}
Run Code Online (Sandbox Code Playgroud)
1)SystemConfiguration向项目添加框架,但不要担心将其包含在任何地方
2)添加托尼百万的版本Reachability.h和Reachability.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
Run Code Online (Sandbox Code Playgroud)
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];
}
Run Code Online (Sandbox Code Playgroud)
重要说明:Reachability该类是项目中使用最多的类之一,因此您可能会遇到与其他项目的命名冲突.如果发生这种情况,您必须将其中一对Reachability.h和Reachability.m文件重命名为其他内容以解决问题.
注意:您使用的域名无关紧要.它只是测试任何域的网关.
can*_*boy 308
我喜欢简单易懂.我这样做的方式是:
//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;
}
Run Code Online (Sandbox Code Playgroud)
然后,每当我想看看我是否有连接时,我都会使用它:
if (![self connected]) {
// Not connected
} else {
// Connected. Do some Internet stuff
}
Run Code Online (Sandbox Code Playgroud)
此方法不会等待更改的网络状态以执行操作.它只是在您要求时测试状态.
And*_*mer 144
使用Apple的Reachability代码,我创建了一个函数,可以正确地检查这个,而不必包含任何类.
在项目中包含SystemConfiguration.framework.
做一些进口:
#import <sys/socket.h>
#import <netinet/in.h>
#import <SystemConfiguration/SystemConfiguration.h>
Run Code Online (Sandbox Code Playgroud)
现在只需调用此函数:
/*
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;
}
Run Code Online (Sandbox Code Playgroud)
它是iOS 5为您测试的.
Dan*_*ser 120
这曾经是正确的答案,但它现在已经过时,因为您应该订阅可达性通知.此方法同步检查:
您可以使用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) { }
Run Code Online (Sandbox Code Playgroud)
SDK不提供Reachability类,而是Apple示例应用程序的一部分.只需下载它,并将Reachability.h/m复制到您的项目中.此外,您必须将SystemConfiguration框架添加到项目中.
Eri*_*rik 81
这是一个非常简单的答案:
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");
Run Code Online (Sandbox Code Playgroud)
该URL应指向一个非常小的网站.我在这里使用谷歌的移动网站,但如果我有一个可靠的网络服务器,我会上传一个只包含一个字符的小文件,以获得最大速度.
如果检查设备是否以某种方式连接到Internet是您想要做的一切,我肯定建议使用这个简单的解决方案.如果您需要知道用户的连接方式,那么使用Reachability是可行的方法.
小心:这会在加载网站时短暂阻止你的线程.在我的情况下,这不是一个问题,但你应该考虑这一点(由Brad指出这一点).
klc*_*r89 72
以下是我在我的应用程序中执行的操作:虽然200状态响应代码不保证任何内容,但它对我来说足够稳定.这不需要像这里发布的NSData答案一样多的加载,因为我只是检查HEAD响应.
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
}
})
}
Run Code Online (Sandbox Code Playgroud)
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
}
}];
}
Run Code Online (Sandbox Code Playgroud)
Ale*_*izi 47
你可以使用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.
Run Code Online (Sandbox Code Playgroud)
Ben*_*oot 33
只有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");}
Run Code Online (Sandbox Code Playgroud)
Bru*_*oga 22
如果您正在使用AFNetworking,则可以使用自己的实现来实现Internet可访问性状态.
最好的使用方法AFNetworking是对类进行子AFHTTPClient类化,并使用此类进行网络连接.
使用此方法的一个优点是,您可以blocks在可达性状态更改时使用设置所需的行为.假设我已经创建了一个单独的子类AFHTTPClient(如AFNetworking文档中的"Subclassing notes" 所述)BKHTTPClient,我会做类似的事情:
BKHTTPClient *httpClient = [BKHTTPClient sharedClient];
[httpClient setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
{
if (status == AFNetworkReachabilityStatusNotReachable)
{
// Not reachable
}
else
{
// Reachable
}
}];
Run Code Online (Sandbox Code Playgroud)
您还可以使用AFNetworkReachabilityStatusReachableViaWWAN和AFNetworkReachabilityStatusReachableViaWiFi枚举检查Wi-Fi或WLAN连接(此处更多内容).
Raj*_*han 14
第1步:将SystemConfiguration框架添加到项目中.
第2步:将以下代码导入您的header文件.
#import <SystemConfiguration/SystemConfiguration.h>
Run Code Online (Sandbox Code Playgroud)
第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;
}
Run Code Online (Sandbox Code Playgroud)类型2:
导入标题:#import "Reachability.h"
- (BOOL)currentNetworkStatus
{
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];
return networkStatus != NotReachable;
}
Run Code Online (Sandbox Code Playgroud)第4步:如何使用:
- (void)CheckInternet
{
BOOL network = [self currentNetworkStatus];
if (network)
{
NSLog(@"Network Available");
}
else
{
NSLog(@"No Network Available");
}
}
Run Code Online (Sandbox Code Playgroud)
Mut*_*awe 12
-(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;
}
}
Run Code Online (Sandbox Code Playgroud)
IOS*_*cks 11
- (void)viewWillAppear:(BOOL)animated
{
NSString *URL = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
return (URL != NULL ) ? YES : NO;
}
Run Code Online (Sandbox Code Playgroud)
或者使用Reachability类.
使用iPhone SDK有两种方法可以检查Internet可用性:
1.检查Google页面是否已打开.
2.可达性等级
有关更多信息,请参阅Reachability(Apple Developer).
Par*_*ara 10
第一:添加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");
}
}
Run Code Online (Sandbox Code Playgroud)
使用 iOS 12 或macOS v10.14 (Mojave) 或更新版本时,您可以使用NWPathMonitor代替 pre-historicReachability类。作为奖励,您可以轻松检测当前的网络连接类型:
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))
Run Code Online (Sandbox Code Playgroud)
更多信息:https : //developer.apple.com/documentation/network/nwpathmonitor
小智 8
首先下载可访问性类,并在您的Xcode中放入reachability.h和reachabilty.m文件.
最好的方法是创建一个通用的Function类(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;
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以通过调用此类方法来检查任何类中的网络连接.
还有另一种使用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;
}
Run Code Online (Sandbox Code Playgroud)
小智 8
下载可访问性文件,https: //gist.github.com/darkseed/1182373
并CFNetwork.framework在框架中添加'SystemConfiguration.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");
}
}
Run Code Online (Sandbox Code Playgroud)
该可达性类是确定以找出是否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:urlReq
returningResponse:&response
error:&error];
NSLog(@"receivedData:%@",receivedData);
if (receivedData !=nil)
{
return YES;
}
else
{
NSLog(@"Data is null");
return NO;
}
}
Run Code Online (Sandbox Code Playgroud)
上面的方法对我来说非常有用,所以每当我尝试将一些数据发送到服务器时,我总是使用这个低超时URLRequest来检查我的Intranet资源的可达性.
要做到这一点非常简单.以下方法将起作用.请确保不允许使用名称传递主机名协议(如HTTP,HTTPS等).
-(BOOL)hasInternetConnection:(NSString*)urlAddress
{
SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [urlAddress UTF8String]);
SCNetworkReachabilityFlags flags;
if (!SCNetworkReachabilityGetFlags(ref, &flags))
{
return NO;
}
return flags & kSCNetworkReachabilityFlagsReachable;
}
Run Code Online (Sandbox Code Playgroud)
它快速简单,无痛.
我认为这是最好的答案.
"是"表示已连接."否"表示断开连接.
#import "Reachability.h"
- (BOOL)canAccessInternet
{
Reachability *IsReachable = [Reachability reachabilityForInternetConnection];
NetworkStatus internetStats = [IsReachable currentReachabilityStatus];
if (internetStats == NotReachable)
{
return NO;
}
else
{
return YES;
}
}
Run Code Online (Sandbox Code Playgroud)
迅捷3 /迅捷4
您必须先导入
import SystemConfiguration
Run Code Online (Sandbox Code Playgroud)
您可以通过以下方法检查互联网连接
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)
}
Run Code Online (Sandbox Code Playgroud)
导入Reachable.h您的类ViewController,并使用以下代码检查连接:
#define hasInternetConnection [[Reachability reachabilityForInternetConnection] isReachable]
if (hasInternetConnection){
// To-do block
}
Run Code Online (Sandbox Code Playgroud)
第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;
}
}
}
Run Code Online (Sandbox Code Playgroud)第4步:调用以下函数:
if (![self checkNetConnection]) {
[GlobalFunctions showAlert:@""
message:@"Please connect to the Internet!"
canBtntitle:nil
otherBtnTitle:@"Ok"];
return;
}
else
{
Log.v("internet is connected","ok");
}
Run Code Online (Sandbox Code Playgroud)检查(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")
}
Run Code Online (Sandbox Code Playgroud)
小智 6
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)
}
Run Code Online (Sandbox Code Playgroud)
像这样调用这个类:
if Reachability.isConnectedToNetwork() == true {
// Do something
} else {
// Do something
}
Run Code Online (Sandbox Code Playgroud)
小智 5
对于我的 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
}
}
Run Code Online (Sandbox Code Playgroud)
使用条件语句,
if Reachability.isConnectedToNetwork() {
// Enter your code here
}
}
else {
print("NO Internet connection")
}
Run Code Online (Sandbox Code Playgroud)
此类几乎在您的应用程序使用 Internet 连接的所有情况下都很有用。如条件为真,则可调用API或执行任务。