如何检查iOS设备上的互联网连接?

我想知道如何检查用户是否通过WIFI或蜂窝数据3G或4G连接到互联网。

另外我不想检查一个网站是否可到达,我想检查是否有设备上的互联网的东西。 我试图通过互联网查看所有我看到的是,他们检查网站是否可达或使用Rechability类。

我想检查当用户打开我的应用程序时是否有networking。

我正在使用Objective-C的Xcode6。

使用此代码并导入Reachability.h文件

 if ([[Reachability reachabilityForInternetConnection]currentReachabilityStatus]==NotReachable) { //connection unavailable } else { //connection available } 

首先从这个链接下载可达性类:
来自Github的可重用性

AppDelegate.h中添加实例的可达性

 @property (nonatomic) Reachability *hostReachability; @property (nonatomic) Reachability *internetReachability; @property (nonatomic) Reachability *wifiReachability; 

在您的AppDelegate中导入可达性,并将其复制并放在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; } 

在你的公共类中添加这个方法。

 /*================================================================================================ 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); } 

希望这可以帮助你在Wifi模式下进行networking连接:

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; } } 

//现在在需要的类中使用它

 - (IBAction)MemberSubmitAction:(id)sender { if([Utils isNetworkAvailable] ==YES){ NSlog(@"Network Connection available"); } } 

试试这个来检查networking连接与否

 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]; 

“可达性”不起作用,因为它不会检测主机是否有响应。 它只会检查客户端是否可以向主机发送数据包。 所以,即使您连接到WiFinetworking,并且WiFi的networking连接断开或服务器closures,您也可以获得“是”,以便进入。

更好的方法是尝试HTTP请求并validation响应。

示例如下:

 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”的更新延迟时间超过了上面代码中提到的超时时间。 你可以在callback里面编码来处理状态。

更新了Swift 4.0和AlamoFire的答案:

我在9月18日发布的答案是不正确的,它只能检测它是否连接到networking,而不是互联网。 这里是使用AlamoFire的正确解决scheme:

1)创build自定义Reachability Observer类:

 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 } 

尝试这个

检查这个链接的可达性文件

可达性

在.m中导入这个文件然后编写代码

//这是检查互联网连接

  BOOL hasInternetConnection = [[Reachability reachabilityForInternetConnection] isReachable]; if (hasInternetConnection) { // your code } 

希望能帮助到你。

 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 } 

使用Alamofire库 :

 let reachabilityManager = NetworkReachabilityManager() let isReachable = reachabilityManager.isReachable if (isReachable) { //Has internet }else{ //No internet }