user6517192
user6517192

Reputation:

Detecting internet connectivity continually

I want my app to detect the internet connection loss automatically. So im using the following code.

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

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

But the problem is that it is not checking the internet connectivity continually. it checks only when the app has become active. How can I be able to check for internet connection continually throughout the app life cycle and throw an warning if internet goes off automatically?

Upvotes: 3

Views: 891

Answers (6)

user8853625
user8853625

Reputation:

You can make use of Reachability framework from iOS and combine it with NSTimer.

Upvotes: -1

Nilesh Jha
Nilesh Jha

Reputation: 1636

Add a observer.

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

Upvotes: 0

TheHungryCub
TheHungryCub

Reputation: 1960

Firstly import in your class: #import "Reachability.h"

Then do like following way:

add an observer for reachability change notification

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

Upvotes: 0

Bhoomi Jagani
Bhoomi Jagani

Reputation: 2423

Add obeserver like this in Reachability method.

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

It will call automatically when your app open/in background mode and it call reachabilityChanged.

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

ChangeInternetConnection you have to add observer to your ViewController to get status when internet changing it's status.

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

Upvotes: 1

PinkeshGjr
PinkeshGjr

Reputation: 8680

Timer is not an efficient way to do this but you can also use timer too.

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

Best way is to use Reachability code. Check here for apple sample code. That has a lot of convenience methods to check internet availability, Wifi/WAN connectivity check etc..

For example:-

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

You can only check this things in background

*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.

Upvotes: 0

Kunal Shah
Kunal Shah

Reputation: 1121

Once your application has launched, you can fire a NSTimer to do the same:

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

Thanks!

Upvotes: 2

Related Questions