如何检查 iOS 设备上的互联网连接?
How to check internet connection on iOS device?
我想知道如何检查用户是否通过 WIFI 或蜂窝数据 3G 或 4G 连接到互联网。
我也不想检查网站是否可以访问,我想检查设备上是否有互联网。我试图浏览互联网,我所看到的只是他们使用 Rechability
class.
检查网站是否可以访问
我想在用户打开我的应用程序时检查他是否有互联网。
我正在使用 Xcode6 和 Objective-C。
使用此代码并导入 Reachability.h
文件
if ([[Reachability reachabilityForInternetConnection]currentReachabilityStatus]==NotReachable)
{
//connection unavailable
}
else
{
//connection available
}
希望这可以帮助您仅在 Wifi 模式下联网:
Utils.h
#import <Foundation/Foundation.h>
@interface Utils : NSObject
+(BOOL)isNetworkAvailable;
@end
utils.m
+ (BOOL)isNetworkAvailable
{
CFNetDiagnosticRef dReference;
dReference = CFNetDiagnosticCreateWithURL (NULL, (__bridge CFURLRef)[NSURL URLWithString:@"www.apple.com"]);
CFNetDiagnosticStatus status;
status = CFNetDiagnosticCopyNetworkStatusPassively (dReference, NULL);
CFRelease (dReference);
if ( status == kCFNetDiagnosticConnectionUp )
{
NSLog (@"Connection is Available");
return YES;
}
else
{
NSLog (@"Connection is down");
return NO;
}
}
//现在在需要的地方使用这个class
- (IBAction)MemberSubmitAction:(id)sender {
if([Utils isNetworkAvailable] ==YES){
NSlog(@"Network Connection available");
}
}
试试这个
检查此 link 的可达性文件
将此文件导入您的 .m 中,然后编写代码
//这是检查网络连接
BOOL hasInternetConnection = [[Reachability reachabilityForInternetConnection] isReachable];
if (hasInternetConnection) {
// your code
}
希望对您有所帮助。
首次下载可达性 类 来自此 Link:
Rechability from Github
在AppDelegate.h中添加可达性实例
@property (nonatomic) Reachability *hostReachability;
@property (nonatomic) Reachability *internetReachability;
@property (nonatomic) Reachability *wifiReachability;
在您的 AppDelegate 中导入 Reachability,然后将此代码复制并粘贴到您的 Appdelegate.m
- (id)init
{
self = [super init];
if (self != nil)
{
//[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
NSString *remoteHostName = @"www.google.com";
self.hostReachability = [Reachability reachabilityWithHostName:remoteHostName];
[self.hostReachability startNotifier];
self.internetReachability = [Reachability reachabilityForInternetConnection];
[self.internetReachability startNotifier];
self.wifiReachability = [Reachability reachabilityForLocalWiFi];
[self.wifiReachability startNotifier];
}
return self;
}
将此方法添加到您的 Common Class。
/*================================================================================================
Check Internet Rechability
=================================================================================================*/
+(BOOL)checkIfInternetIsAvailable
{
BOOL reachable = NO;
NetworkStatus netStatus = [APP_DELEGATE1.internetReachability currentReachabilityStatus];
if(netStatus == ReachableViaWWAN || netStatus == ReachableViaWiFi)
{
reachable = YES;
}
else
{
reachable = NO;
}
return reachable;
}
注意APP_DELEGATE1是AppDelegate的一个实例
/* AppDelegate object */
#define APP_DELEGATE1 ((AppDelegate*)[[UIApplication sharedApplication] delegate])
您可以使用此方法在应用中的任何位置检查互联网连接。
很简单,您可以使用以下方法检查互联网连接。
-(BOOL)IsConnectionAvailable
{
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];
return !(networkStatus == NotReachable);
}
Reachability* reachability = [Reachability reachabilityWithHostName:@"www.google.com"];
NetworkStatus internetStatus = [reachability currentReachabilityStatus];
if(remoteHostStatus == ReachableViaWWAN || remoteHostStatus == ReachableViaWiFi)
{
//my web-dependent code
}
else {
//there-is-no-connection warning
}
试试这个来检查互联网连接与否
NSURL *url = [NSURL URLWithString:@"http://www.appleiphonecell.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:nil delegateQueue: [NSOperationQueue mainQueue]];
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:headRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
if (!error && response)
{
block([(NSHTTPURLResponse *)response statusCode] == 200);
}else{
block(FALSE);
}
}];
[dataTask resume];
'Reachability' 不起作用,因为它不会检测主机是否有响应。它只会检查客户端是否可以向主机发送数据包。因此,即使您连接到 WiFi 网络并且 WiFi 的互联网已关闭或服务器已关闭,您也会获得 "YES" 的可达性。
更好的方法是尝试 HTTP 请求并验证响应。
示例如下:
NSURL *pageToLoadUrl = [[NSURL alloc] initWithString:@"https://www.google.com/"];
NSMutableURLRequest *pageRequest = [NSMutableURLRequest requestWithURL:pageToLoadUrl];
[pageRequest setTimeoutInterval:2.0];
AFHTTPRequestOperation *pageOperation = [[AFHTTPRequestOperation alloc] initWithRequest:pageRequest];
AFRememberingSecurityPolicy *policy = [AFRememberingSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
[policy setDelegate:self];
currentPageOperation.securityPolicy = policy;
if (self.ignoreSSLCertificate) {
NSLog(@"Warning - ignoring invalid certificates");
currentPageOperation.securityPolicy.allowInvalidCertificates = YES;
}
[pageOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
internetActive = YES;
} failure:^(AFHTTPRequestOperation *operation, NSError *error){
NSLog(@"Error:------>%@", [error description]);
internetActive = NO;
}];
[pageOperation start];
唯一的问题是 "internetActive" 的更新延迟到上述代码中提到的超时时间。您可以在回调中编写代码以对状态进行操作。
let reachabilityManager = NetworkReachabilityManager()
let isReachable = reachabilityManager.isReachable
if (isReachable) {
//Has internet
}else{
//No internet
}
Swift 4.0 和 AlamoFire 的更新答案:
我在9月18日发布的答案是错误的,它只检测是否连接到网络,而不是互联网。这是使用 AlamoFire 的正确解决方案:
1) 创建自定义 Reachability Observer class:
import Alamofire
class ReachabilityObserver {
fileprivate let reachabilityManager = NetworkReachabilityManager()
fileprivate var reachabilityStatus: NetworkReachabilityManager.NetworkReachabilityStatus = .unknown
var isOnline: Bool {
if (reachabilityStatus == .unknown || reachabilityStatus == .notReachable){
return false
}else{
return true
}
}
static let sharedInstance = ReachabilityObserver()
fileprivate init () {
reachabilityManager?.listener = {
[weak self] status in
self?.reachabilityStatus = status
NotificationCenter.default.post(
name: NSNotification.Name(rawValue: ClickUpConstants.ReachabilityStateChanged),
object: nil)
}
reachabilityManager?.startListening()
}
}
2) 在应用程序启动时初始化
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
_ = ReachabilityObserver.sharedInstance
return true
}
3) 在您的应用中的任何地方使用它来检测是否在线,例如在视图中是否加载,或何时发生操作
if (ReachabilityObserver.sharedInstance.isOnline){
//User is online
}else{
//User is not online
}
我想知道如何检查用户是否通过 WIFI 或蜂窝数据 3G 或 4G 连接到互联网。
我也不想检查网站是否可以访问,我想检查设备上是否有互联网。我试图浏览互联网,我所看到的只是他们使用 Rechability
class.
我想在用户打开我的应用程序时检查他是否有互联网。
我正在使用 Xcode6 和 Objective-C。
使用此代码并导入 Reachability.h
文件
if ([[Reachability reachabilityForInternetConnection]currentReachabilityStatus]==NotReachable)
{
//connection unavailable
}
else
{
//connection available
}
希望这可以帮助您仅在 Wifi 模式下联网:
Utils.h
#import <Foundation/Foundation.h>
@interface Utils : NSObject
+(BOOL)isNetworkAvailable;
@end
utils.m
+ (BOOL)isNetworkAvailable
{
CFNetDiagnosticRef dReference;
dReference = CFNetDiagnosticCreateWithURL (NULL, (__bridge CFURLRef)[NSURL URLWithString:@"www.apple.com"]);
CFNetDiagnosticStatus status;
status = CFNetDiagnosticCopyNetworkStatusPassively (dReference, NULL);
CFRelease (dReference);
if ( status == kCFNetDiagnosticConnectionUp )
{
NSLog (@"Connection is Available");
return YES;
}
else
{
NSLog (@"Connection is down");
return NO;
}
}
//现在在需要的地方使用这个class
- (IBAction)MemberSubmitAction:(id)sender {
if([Utils isNetworkAvailable] ==YES){
NSlog(@"Network Connection available");
}
}
试试这个
检查此 link 的可达性文件
将此文件导入您的 .m 中,然后编写代码
//这是检查网络连接
BOOL hasInternetConnection = [[Reachability reachabilityForInternetConnection] isReachable];
if (hasInternetConnection) {
// your code
}
希望对您有所帮助。
首次下载可达性 类 来自此 Link:
Rechability from Github
在AppDelegate.h中添加可达性实例
@property (nonatomic) Reachability *hostReachability;
@property (nonatomic) Reachability *internetReachability;
@property (nonatomic) Reachability *wifiReachability;
在您的 AppDelegate 中导入 Reachability,然后将此代码复制并粘贴到您的 Appdelegate.m
- (id)init
{
self = [super init];
if (self != nil)
{
//[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
NSString *remoteHostName = @"www.google.com";
self.hostReachability = [Reachability reachabilityWithHostName:remoteHostName];
[self.hostReachability startNotifier];
self.internetReachability = [Reachability reachabilityForInternetConnection];
[self.internetReachability startNotifier];
self.wifiReachability = [Reachability reachabilityForLocalWiFi];
[self.wifiReachability startNotifier];
}
return self;
}
将此方法添加到您的 Common Class。
/*================================================================================================
Check Internet Rechability
=================================================================================================*/
+(BOOL)checkIfInternetIsAvailable
{
BOOL reachable = NO;
NetworkStatus netStatus = [APP_DELEGATE1.internetReachability currentReachabilityStatus];
if(netStatus == ReachableViaWWAN || netStatus == ReachableViaWiFi)
{
reachable = YES;
}
else
{
reachable = NO;
}
return reachable;
}
注意APP_DELEGATE1是AppDelegate的一个实例
/* AppDelegate object */
#define APP_DELEGATE1 ((AppDelegate*)[[UIApplication sharedApplication] delegate])
您可以使用此方法在应用中的任何位置检查互联网连接。
很简单,您可以使用以下方法检查互联网连接。
-(BOOL)IsConnectionAvailable
{
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];
return !(networkStatus == NotReachable);
}
Reachability* reachability = [Reachability reachabilityWithHostName:@"www.google.com"];
NetworkStatus internetStatus = [reachability currentReachabilityStatus];
if(remoteHostStatus == ReachableViaWWAN || remoteHostStatus == ReachableViaWiFi)
{
//my web-dependent code
}
else {
//there-is-no-connection warning
}
试试这个来检查互联网连接与否
NSURL *url = [NSURL URLWithString:@"http://www.appleiphonecell.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:nil delegateQueue: [NSOperationQueue mainQueue]];
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:headRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
if (!error && response)
{
block([(NSHTTPURLResponse *)response statusCode] == 200);
}else{
block(FALSE);
}
}];
[dataTask resume];
'Reachability' 不起作用,因为它不会检测主机是否有响应。它只会检查客户端是否可以向主机发送数据包。因此,即使您连接到 WiFi 网络并且 WiFi 的互联网已关闭或服务器已关闭,您也会获得 "YES" 的可达性。
更好的方法是尝试 HTTP 请求并验证响应。
示例如下:
NSURL *pageToLoadUrl = [[NSURL alloc] initWithString:@"https://www.google.com/"];
NSMutableURLRequest *pageRequest = [NSMutableURLRequest requestWithURL:pageToLoadUrl];
[pageRequest setTimeoutInterval:2.0];
AFHTTPRequestOperation *pageOperation = [[AFHTTPRequestOperation alloc] initWithRequest:pageRequest];
AFRememberingSecurityPolicy *policy = [AFRememberingSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
[policy setDelegate:self];
currentPageOperation.securityPolicy = policy;
if (self.ignoreSSLCertificate) {
NSLog(@"Warning - ignoring invalid certificates");
currentPageOperation.securityPolicy.allowInvalidCertificates = YES;
}
[pageOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
internetActive = YES;
} failure:^(AFHTTPRequestOperation *operation, NSError *error){
NSLog(@"Error:------>%@", [error description]);
internetActive = NO;
}];
[pageOperation start];
唯一的问题是 "internetActive" 的更新延迟到上述代码中提到的超时时间。您可以在回调中编写代码以对状态进行操作。
let reachabilityManager = NetworkReachabilityManager()
let isReachable = reachabilityManager.isReachable
if (isReachable) {
//Has internet
}else{
//No internet
}
Swift 4.0 和 AlamoFire 的更新答案:
我在9月18日发布的答案是错误的,它只检测是否连接到网络,而不是互联网。这是使用 AlamoFire 的正确解决方案:
1) 创建自定义 Reachability Observer class:
import Alamofire
class ReachabilityObserver {
fileprivate let reachabilityManager = NetworkReachabilityManager()
fileprivate var reachabilityStatus: NetworkReachabilityManager.NetworkReachabilityStatus = .unknown
var isOnline: Bool {
if (reachabilityStatus == .unknown || reachabilityStatus == .notReachable){
return false
}else{
return true
}
}
static let sharedInstance = ReachabilityObserver()
fileprivate init () {
reachabilityManager?.listener = {
[weak self] status in
self?.reachabilityStatus = status
NotificationCenter.default.post(
name: NSNotification.Name(rawValue: ClickUpConstants.ReachabilityStateChanged),
object: nil)
}
reachabilityManager?.startListening()
}
}
2) 在应用程序启动时初始化
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
_ = ReachabilityObserver.sharedInstance
return true
}
3) 在您的应用中的任何地方使用它来检测是否在线,例如在视图中是否加载,或何时发生操作
if (ReachabilityObserver.sharedInstance.isOnline){
//User is online
}else{
//User is not online
}