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

时间:2015-07-31 09:22:53

标签: ios objective-c cocoa-touch reachability

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

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

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

我正在使用带有Objective-C的Xcode6。

10 个答案:

答案 0 :(得分:21)

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

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

答案 1 :(得分:5)

首先从此链接下载可达性类:
enter image description here

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

在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])  

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

答案 2 :(得分:3)

希望这可以帮助您仅在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");
   }

 }

答案 3 :(得分:3)

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

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

    NetworkStatus networkStatus = [reachability currentReachabilityStatus];

    return !(networkStatus == NotReachable);    
}

答案 4 :(得分:2)

尝试此操作以检查是否连接了互联网

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

答案 5 :(得分:1)

&#39;可达性&#39;不起作用,因为它不会检测主机是否有响应。它只会检查客户端是否可以向主机发送数据包。因此,即使您连接到WiFi网络并且WiFi的互联网已关闭或服务器已关闭,您也会得到一个&#34; YES&#34;可达性。

更好的方法是尝试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];

唯一的问题是&#34; internetActive&#34;更新延迟到上面代码中提到的超时。您可以在回调内部编码以对状态进行操作。

答案 6 :(得分:1)

更新了Swift 4.0&amp;的答案AlamoFire:

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

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)在应用启动时初始化

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
}

答案 7 :(得分:0)

试试这个

检查此链接是否有可达性文件

Reachability

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

//这是检查互联网连接

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

希望它有所帮助。

答案 8 :(得分:0)

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
}

答案 9 :(得分:0)

使用Alamofire library

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

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