持续检测互联网连接

时间:2016-08-01 05:29:01

标签: ios objective-c reachability

我希望我的应用能够自动检测互联网连接丢失。所以即时使用以下代码。

- (void)applicationDidBecomeActive:(UIApplication *)application {

    Reachability *networkReachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
    if (networkStatus == NotReachable) {
        [Settings hideSpinner];
         //Show no internet connectivity dialog.
    } else {
    }
}

但问题是它不是在不断检查互联网连接。 它仅在应用程序变为活动状态时进行检查。如何在整个应用程序生命周期内持续检查互联网连接,并在互联网自动关闭时发出警告?

6 个答案:

答案 0 :(得分:3)

启动应用程序后,您可以触发NSTimer执行相同的操作:

- (void)applicationDidBecomeActive:(UIApplication *)application {
   NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0f
                                              target:self
                                            selector:@selector(checkForConnectivity)
                                            userInfo:nil
                                             repeats:YES];
}

-(void)checkForConnectivity {
       Reachability *networkReachability = [Reachability reachabilityForInternetConnection];
       NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
       if (networkStatus == NotReachable) {
              //No internet connectivity - perform required action
       }
       else {
              //Internet connectivity is valid
      }
}

谢谢!

答案 1 :(得分:2)

在Reachability方法中添加这样的obeserver。

1) [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged :) name:kReachabilityChangedNotification object:nil] ;

当您的应用打开/处于后台模式时,它会自动调用,并且会调用reachabilityChanged。

2) [[NSNotificationCenter defaultCenter] postNotificationName:@" ChangeInternetConnection"对象:无];

ChangeInternetConnection 您必须在 ViewController 中添加观察者,以便在互联网更改状态时获取状态。

 - (void) checkInternetConnetion {

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];

        //NSString *remoteHostName = @"www.apple.com";


    self.internetReachability = [Reachability reachabilityForInternetConnection];
        [self.internetReachability startNotifier];
        [self updateInterfaceWithReachability:self.internetReachability];
    }


    #pragma mark - Reachability Methods

    - (void)updateInterfaceWithReachability:(Reachability *)reachability {
     if (reachability == self.internetReachability) {
            [self checkStatus:reachability];
        }

        if (reachability == self.wifiReachability) {
            [self checkStatus:reachability];
        }
    }


    -(void)checkStatus :(Reachability *)reachability {

        NetworkStatus netStatus = [reachability currentReachabilityStatus];
        BOOL connectionRequired = [reachability connectionRequired];
        NSString* statusString = @"";

        switch (netStatus) {

            case NotReachable: {

               self.isInternetOn = FALSE;

                break;
            }

            case ReachableViaWWAN: {
                self.isInternetOn = TRUE;

                break;
            }
            case ReachableViaWiFi: {
                self.isInternetOn = TRUE;

                break;
            }
        }



        [[NSNotificationCenter defaultCenter] postNotificationName:@"ChangeInternetConnection" object:nil];

      }

    - (void) reachabilityChanged:(NSNotification *)note {

        Reachability* curReach = [note object];
        NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
        [self updateInterfaceWithReachability:curReach];
    }

答案 2 :(得分:1)

首先在您的课程中导入:#import "Reachability.h"

然后按照以下方式进行:

添加可达性更改通知的观察者

[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityChanged:)
                                                 name:kReachabilityChangedNotification object:nil];


-(BOOL)reachabilityChanged:(NSNotification*)note
{
    BOOL status =YES;

    NSLog(@"reachabilityChanged");

    Reachability * reach = [note object];

    if([reach isReachable])
    {
        status = YES;

        NSLog(@"your network is Available");
    }

    else

    {
        status = NO;

//Do something here

    }
    return status;
}

答案 3 :(得分:1)

计时器不是一种有效的方法,但你也可以使用计时器。

- (void)applicationDidBecomeActive:(UIApplication *)application 
{
       NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0f
                                                  target:self
                                                selector:@selector(handleConnectivity)
                                                userInfo:nil
                                                 repeats:YES];
}
-(void)handleConnectivity
{
    Reachability *networkReachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
    if (networkStatus == NotReachable)
    {
        //No internet connectivity - perform required action
    }
    else
    {
        //Internet connectivity is valid
    }
}

最好的方法是使用Reachability代码。 Check here for apple sample code.这有很多方便的方法来检查互联网可用性,Wifi / WAN连接检查等。

例如: -

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkChanged:) name:kReachabilityChangedNotification object:nil];

reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];

- (void)networkChanged:(NSNotification *)notification
{

  NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];

  if(remoteHostStatus == NotReachable) { NSLog(@"not reachable");}
  else if (remoteHostStatus == ReachableViaWiFiNetwork) { NSLog(@"wifi"); }
  else if (remoteHostStatus == ReachableViaCarrierDataNetwork) { NSLog(@"carrier"); }
}

你只能在后台检查这些东西

  

* audio-该应用程序在后台播放可听内容给用户。 (此内容包括流式音频或视频内容   使用AirPlay。)

     

* location - 该应用程序可让用户随时了解其位置,即使它在后台运行也是如此。

     

* voip-该应用程序使用户能够使用Internet连接拨打电话。

     

*报亭 - 内容 - 该应用是一个报亭应用,可在后台下载和处理杂志或报纸内容。

     

* external-accessory-该应用程序适用于需要通过外部定期提供更新的硬件配件   附件框架。

     

* bluetooth-central-该应用程序与蓝牙配件配合使用,需要通过Core Bluetooth定期提供更新   框架。

     

* bluetooth-peripheral-该应用程序通过Core Bluetooth框架支持外设模式下的蓝牙通信。

答案 4 :(得分:1)

添加观察者。

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(reachabilityChanged:)
                                             name:kReachabilityChangedNotification
                                           object:nil];

-(BOOL)reachabilityChanged:(NSNotification*)note
{
    BOOL status =YES;
    NSLog(@"reachability is changed");

    Reachability * reach = [note object];

    if([reach isReachable])
    {
        status = YES;
        NSLog(@"NetWork is Available. Please go ahead");
    }
    else
    {
        status = NO;
        NSLog(@"NetWork is not Available. Please check your connection.");
    }
    return status;
}

答案 5 :(得分:-1)

您可以使用iOS中的Reachability框架并将其与NSTimer结合使用。