我想查看我是否在iOS上使用Cocoa Touch库或使用Cocoa库在macOS上建立了Internet连接。
我想出了一个使用NSURL
做到这一点的方法。我这样做的方式似乎有点不可靠(因为即使谷歌有一天会失败并依赖第三方看起来很糟糕),而且如果谷歌没有回应,我可以查看其他网站的回复,在我的应用程序中看起来似乎很浪费并且不必要的开销
- (BOOL) connectedToInternet
{
NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
return ( URLString != NULL ) ? YES : NO;
}
我做得不好,(更不用说stringWithContentsOfURL
在iOS 3.0和macOS 10.4中被弃用)如果是这样,有什么更好的方法来实现这一目标?
重要说明:此检查应始终异步执行。下面的大部分答案都是同步的,所以要小心,否则你会冻结你的应用程序。
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")
}
1)将SystemConfiguration
框架添加到项目中,但不要担心将其包含在任何地方
2)将Tony Million的版本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
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
文件重命名为其他内容以解决此问题。
注意:您使用的域名无关紧要。它只是测试任何域的网关。
只有Reachability类已更新。您现在可以使用:
Reachability
关于iOS 5 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");}
。不是我的! =)
这里有一个漂亮的,ARC和GCD使用的可达性现代化:
如果您正在使用Reachability,则可以使用自己的实现来实现Internet可访问性状态。
使用AFNetworking
的最佳方法是继承AFNetworking
类并使用此类进行网络连接。
使用此方法的一个优点是,您可以使用AFHTTPClient
在可达性状态更改时设置所需的行为。假设我已经创建了blocks
的单例子类(如AFHTTPClient
上的“Subclassing notes”所述),命名为AFNetworking docs,我会做类似的事情:
BKHTTPClient
您还可以使用BKHTTPClient *httpClient = [BKHTTPClient sharedClient];
[httpClient setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
{
if (status == AFNetworkReachabilityStatusNotReachable)
{
// Not reachable
}
else
{
// Reachable
}
}];
和AFNetworkReachabilityStatusReachableViaWWAN
枚举(AFNetworkReachabilityStatusReachableViaWiFi
)检查Wi-Fi或WLAN连接。
我已经在more here中使用了代码,它似乎工作正常(阅读整个线程!)。
我没有用各种可能的连接(如ad hoc Wi-Fi)对其进行详尽的测试。
非常简单....尝试以下步骤:
第1步:将this discussion框架添加到您的项目中。
第2步:将以下代码导入SystemConfiguration
文件。
header
第3步:使用以下方法
#import <SystemConfiguration/SystemConfiguration.h>
- (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;
}
#import "Reachability.h"
第4步:如何使用:
- (BOOL)currentNetworkStatus
{
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];
return networkStatus != NotReachable;
}
- (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;
}
}
或者使用Reachability类。
使用iPhone SDK有两种方法可以检查Internet可用性:
1.检查Google页面是否已打开。
2.可达性等级
有关更多信息,请参阅- (void)viewWillAppear:(BOOL)animated
{
NSString *URL = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
return (URL != NULL ) ? YES : NO;
}
(Apple Developer)。
使用Reachability。它比自己添加库和编写代码更容易。
我喜欢简单易懂。我这样做的方式是:
//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
}
此方法不会等待更改的网络状态以执行操作。它只是在您要求时测试状态。
首先下载可达性类,并在您的#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文件。
最好的方法是创建一个通用的Function类(NSObject),以便您可以在任何类中使用它。这是网络连接可达性检查的两种方法:
Xcode
现在,您可以通过调用此类方法来检查任何类中的网络连接。
还有另一种使用iPhone SDK检查Internet连接的方法。
尝试为网络连接实现以下代码。
+(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;
}
我发现它简单易用的库#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;
}
。
第一:在框架中添加CFNetwork.framework
代码:CFNetwork.framework
ViewController.m
Reachability类可以确定设备是否可以使用Internet连接......
但是在访问Intranet资源的情况下:
使用可访问性类对Intranet服务器进行Ping操作始终返回true。
因此,在这种情况下,快速解决方案是创建一个名为- (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");
}
}
的Web方法以及该服务上的其他Web方法。 pingme
应该返回一些东西。
所以我在常用函数上编写了以下方法
pingme
上面的方法对我来说非常有用,所以每当我尝试将一些数据发送到服务器时,我总是使用这个低超时URLRequest检查我的Intranet资源的可达性。
要做到这一点非常简单。以下方法将起作用。请确保不允许使用名称传递主机名协议(如HTTP,HTTPS等)。
-(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;
}
}
它快速简单,无痛。
除了可达性,您还可以使用-(BOOL)hasInternetConnection:(NSString*)urlAddress
{
SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [urlAddress UTF8String]);
SCNetworkReachabilityFlags flags;
if (!SCNetworkReachabilityGetFlags(ref, &flags))
{
return NO;
}
return flags & kSCNetworkReachabilityFlagsReachable;
}
。它工作得非常好,并且易于集成。
在#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
}
- (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;
}
}
}
使用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为您测试的。
检查(iOS)Xcode 8,Swift 3.0中的Internet连接可用性
这是检查网络可用性的简单方法,例如我们的设备是否连接到任何网络。我已设法将其翻译为Swift 3.0,并在此处为最终代码。现有的Apple Reachability类和其他第三方库似乎太复杂,无法转换为Swift。
这适用于3G,4G和WiFi连接。
不要忘记将“SystemConfiguration.framework”添加到项目构建器中。
if (![self checkNetConnection]) {
[GlobalFunctions showAlert:@""
message:@"Please connect to the Internet!"
canBtntitle:nil
otherBtnTitle:@"Ok"];
return;
}
else
{
Log.v("internet is connected","ok");
}
这曾经是正确的答案,但它现在已经过时,因为您应该订阅可达性通知。此方法同步检查:
您可以使用Apple的Reachability类。它还允许您检查是否启用了Wi-Fi:
Reachability* reachability = [Reachability sharedReachability];
[reachability setHostName:@"www.example.com"]; // Set your host name here
NetworkStatus remoteHostStatus = [reachability remoteHostStatus];
if (remoteHostStatus == NotReachable) { }
else if (remoteHostStatus == ReachableViaWiFiNetwork) { }
else if (remoteHostStatus == ReachableViaCarrierDataNetwork) { }
SDK中不提供Reachability类,而是this Apple sample application的一部分。只需下载它,并将Reachability.h / m复制到您的项目中。此外,您必须将SystemConfiguration框架添加到项目中。
这是一个非常简单的答案:
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应指向一个非常小的网站。我在这里使用谷歌的移动网站,但如果我有一个可靠的网络服务器,我会上传一个只包含一个字符的小文件,以获得最大速度。
如果检查设备是否以某种方式连接到Internet是您想要做的一切,我肯定建议使用这个简单的解决方案。如果您需要知道用户的连接方式,那么使用Reachability是可行的方法。
小心:这会在加载网站时短暂阻止你的线程。在我的情况下,这不是一个问题,但你应该考虑这一点(由Brad指出这一点)。
以下是我在我的应用程序中执行的操作:虽然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
}
})
}
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
}
}];
}
Apple提供sample code来检查不同类型的网络可用性。另外,iPhone开发者手册中还有一个example。
注意:有关使用Apple的可访问性代码,请参阅@KHG对此答案的评论。
你可以使用qzxswpoi by(Reachability
)。
available here
Apple提供了一个示例应用程序,它正是如下:
#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.