【问题标题】:How to check internet connection on iOS device? [duplicate]如何在 iOS 设备上检查互联网连接? [复制]
【发布时间】:2015-10-22 22:07:53
【问题描述】:

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

我也不想检查网站是否可以访问,我想检查设备上是否有互联网。我试图查看互联网,我看到的只是他们使用 Rechability 类检查网站是否可访问。

我想在用户打开我的应用程序时检查他是否有互联网。

我正在使用 Xcode6 和 Objective-C。

【问题讨论】:

标签: ios objective-c cocoa-touch reachability


【解决方案1】:

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

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

【讨论】:

  • 我找不到 Reachability.h 文件!
  • @SniperCoder 下载这个类并将其放入您的项目中。 github.com/tonymillion/Reachability
  • @SniperCoder 尝试#import "Reachability.h"。在我的 x 代码中,它不会显示在自动建议中,但代码会编译
  • 我已经添加了可达性类,并尝试使用您的答案检查连接验证。即使我连接到 WiFi 但它没有互联网连接,它也总是可以访问。 WiFi 并不意味着它有互联网连接。我想验证互联网连接,即使它有 WiFi 连接。你能帮帮我吗?
【解决方案2】:

首先从此链接下载可达性类:
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;
}  

在您的公共类中添加此方法。

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

您可以使用此方法在应用程序中的任何位置检查互联网连接。

【讨论】:

    【解决方案3】:

    很简单,您可以使用以下方法检查互联网连接。

    -(BOOL)IsConnectionAvailable
    {
        Reachability *reachability = [Reachability reachabilityForInternetConnection];
    
        NetworkStatus networkStatus = [reachability currentReachabilityStatus];
    
        return !(networkStatus == NotReachable);    
    }
    

    【讨论】:

    • 我试过这样。但即使我连接到 WiFi 但它没有互联网连接,它总是可以访问的。 WiFi 并不意味着它有互联网连接。我想验证互联网连接,即使它有 WiFi 连接。你能帮帮我吗?
    【解决方案4】:

    希望这有助于您仅在 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;
          }
        }
    

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

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

    【讨论】:

    • 如果设备已连接到 3G/LTE,此解决方案将不起作用。
    【解决方案5】:

    试试这个检查互联网连接与否

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

    【讨论】:

      【解决方案6】:

      “可达性”不起作用,因为它不会检测是否有来自主机的响应。它只会检查客户端是否可以向主机发送数据包。因此,即使您已连接到 WiFi 网络并且 WiFi 的互联网已关闭或服务器已关闭,您也会获得“是”的可访问性。

      更好的方法是尝试 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”会延​​迟更新,直到上述代码中提到的超时。您可以在回调中编写代码来处理状态。

      【讨论】:

        【解决方案7】:

        Swift 4.0 和 AlamoFire 的更新答案:

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

        1) 创建自定义的可达性观察者类:

        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
        }
        

        【讨论】:

          【解决方案8】:

          试试这个

          检查此链接以获取可达性文件

          Reachability

          将此文件导入您的 .m 中,然后编写代码

          //这是检查网络连接

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

          希望对你有帮助。

          【讨论】:

            【解决方案9】:
            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
            }
            

            【讨论】:

              【解决方案10】:

              使用Alamofire library

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

              【讨论】:

              • 这也只检查设备是否连接到网络,而不检查网络是否连接到互联网。
              • 请看我的新答案
              猜你喜欢
              • 2018-01-29
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-07-27
              • 1970-01-01
              • 2012-05-18
              • 1970-01-01
              • 2015-08-20
              相关资源
              最近更新 更多