Obj-Swift
Obj-Swift

Reputation: 2942

Trigger action immediately after connection is available

I want to trigger an action once the connection is available. There are solutions available which allows manually checking internet connection. One way i find is using NSTimer to check for internet connection during fixed intervals. But is it the most effective way to check for it? if Not, What is the right solution for this?

Upvotes: 0

Views: 412

Answers (2)

nsgulliver
nsgulliver

Reputation: 12671

Here how you can register the observer and listen to it, Your application will be listening to kReachabilityChangedNotification & prompt you whenever status of network changes.

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

    internetReachable = [[Reachability reachabilityForInternetConnection] retain];
    [internetReachable startNotifier];



-(void) reachabilityHasChanged:(NSNotification *)notice
{
    // called after network status changes
    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
    switch (internetStatus)
    {
        case NotReachable:
        {
            NSLog(@"The internet is down.");


            break;
        }
        case ReachableViaWiFi:
        {
            NSLog(@"The internet is working via WIFI.");


            break;
        }
        case ReachableViaWWAN:
        {
            NSLog(@"The internet is working via WWAN.");


            break;
        }
    }
 }

Upvotes: 2

Lithu T.V
Lithu T.V

Reputation: 20021

Check reachability code provided by apple.In appdelegate.m you can see this method.It will notify the network change.Work on it

//Called by Reachability whenever status changes.
- (void) reachabilityChanged: (NSNotification* )note
{
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    [self updateInterfaceWithReachability: curReach];
}

Upvotes: 0

Related Questions