持续检测互联网连接

Detecting internet connectivity continually

我希望我的应用程序自动检测互联网连接中断。所以我使用以下代码。

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

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

但问题是它没有持续检查互联网连接。 它仅在应用程序激活时检查。我如何才能在整个应用程序生命周期中持续检查互联网连接并在互联网自动关闭时发出警告?

首先导入你的class:#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;
}

计时器不是执行此操作的有效方法,但您也可以使用计时器。

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

最好的方法是使用可达性代码。 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—The app plays audible content to the user while in the background. (This content includes streaming audio or video content using AirPlay.)

*location—The app keeps users informed of their location, even while it is running in the background.

*voip—The app provides the ability for the user to make phone calls using an Internet connection.

*newsstand-content—The app is a Newsstand app that downloads and processes magazine or newspaper content in the background.

*external-accessory—The app works with a hardware accessory that needs to deliver updates on a regular schedule through the External Accessory framework.

*bluetooth-central—The app works with a Bluetooth accessory that needs to deliver updates on a regular schedule through the Core Bluetooth framework.

*bluetooth-peripheral—The app supports Bluetooth communication in peripheral mode through the Core Bluetooth framework.

在 Reachability 方法中像这样添加观察者。

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

它会在您的应用程序 open/in 后台模式时自动调用并调用 reachabilityChanged。

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

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

应用程序启动后,您可以启动 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
      }
}

谢谢!

添加一个观察者。

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

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