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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31742601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 07:05:27  来源:igfitidea点击:

How to check internet connection on iOS device?

iosobjective-ccocoa-touchreachability

提问by SniperCoder

I'm wondering how I can check if the user is connect to internet through WIFI or cellular data 3G or 4G.

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

Also I don't want to check if a website is reachable or not, the thing that I want to check if there is internet on the device or not. I tried to look over the internet all that I see is that they check if the website is reachable or not using the Rechabilityclass.

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

I want to check if the user has internet or not when he opens my application.

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

I'm using Xcode6 with Objective-C.

我将 Xcode6 与 Objective-C 一起使用。

回答by Jay Bhalani

Use this code and import Reachability.hfile

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

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

回答by Mihir Oza

First Download Reachability classes from this Link:
Rechability from Github

首先从此链接下载 Reachability 类:
来自 Github 的 Rechability

Add Instance of Reachability in AppDelegate.h

AppDelegate.h 中添加 Reachability 实例

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

Import Reachability in your AppDelegate and just copy and past this code in your Appdelegate.m

在您的 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;
}  

Add this method in your 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;
}  

Note that APP_DELEGATE1Is an instance of AppDelegate

注意APP_DELEGATE1是 AppDelegate 的一个实例

/* AppDelegate object */
#define APP_DELEGATE1 ((AppDelegate*)[[UIApplication sharedApplication] delegate])  

You can check internet connectivity anywhere in app using this method.

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

回答by Dibin77

it's simple , you can use following method to check internet connection .

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

-(BOOL)IsConnectionAvailable
{
    Reachability *reachability = [Reachability reachabilityForInternetConnection];

    NetworkStatus networkStatus = [reachability currentReachabilityStatus];

    return !(networkStatus == NotReachable);    
}

回答by soumya

Hope this helps you to network in Wifi mode only:

希望这可以帮助您仅在 Wifi 模式下联网:

Utils.h

实用程序

 #import <Foundation/Foundation.h>
 @interface Utils : NSObject

 +(BOOL)isNetworkAvailable;

 @end

utils.m

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

//Now use this in required class

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

- (IBAction)MemberSubmitAction:(id)sender {
   if([Utils isNetworkAvailable] ==YES){

      NSlog(@"Network Connection available");
   }

 }

回答by DURGESH

Try This to check internet connected or not

试试这个来检查互联网是否连接

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

回答by Abhijith C R

'Reachability' doesn't work since it won't detect if there is a response from the host or not. It will just check if the client can send out a packet to the host. So even if you are connected to a WiFi network and the WiFi's internet is down or the server is down, you will get a "YES" for reachability.

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

A better method is to try an HTTP request and verify the response.

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

Example below:

下面的例子:

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

Only catch is that the "internetActive" gets updated with a delay upto the timeout mentioned in the above code. You can code inside the callback to act on the status.

唯一的问题是“internetActive”会延​​迟更新到上面代码中提到的超时时间。您可以在回调中编码以对状态采取行动。

回答by Josh O'Connor

Updated answer for Swift 4.0 & AlamoFire:

Swift 4.0 和 AlamoFire 的更新答案:

The answer I posted on Sept 18 is incorrect, it only detects if it is connected to network, not internet. Here is the correct solution using AlamoFire:

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

1) Create custom Reachability Observer class:

1) 创建自定义 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) Initialize on app start up

2)在应用程序启动时初始化

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
     _ = ReachabilityObserver.sharedInstance
     return true
}

3) Use this anywhere in your app to detect if online, such as in view did load, or when action occurs

3)在你的应用程序的任何地方使用它来检测是否在线,例如在视图中加载,或者何时发生动作

if (ReachabilityObserver.sharedInstance.isOnline){
    //User is online
}else{
    //User is not online
}

回答by Josh O'Connor

Using Alamofire library:

使用Alamofire 库

let reachabilityManager = NetworkReachabilityManager()
let isReachable = reachabilityManager.isReachable

if (isReachable) {
    //Has internet
}else{
    //No internet
}

回答by Pradumna Patil

Try this

尝试这个

check this link for Reachability file

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

Reachability

可达性

import this file in your .m and then write code

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

//This is to check internet connection

//这是检查互联网连接

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

Hope it helps.

希望能帮助到你。

回答by Anurag Sharma

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
}