user2604504
user2604504

Reputation: 717

Where to check for network connection in iOS app

I'm working on an iOS application that deals with web service. I am using this code to detect if I have a web connection. If I don't have an internet connection I'm going to show a view that says there is no internet connection (similar to how the iOS app store does it). My issue is that I'm not sure which method to put this code in.

I would like it so that every time the user opens the app and/or switches to the app from using another app (i.e. my app is open in the background and the user switches to it) it checks the network status. I thought putting it in my app delegate would work but it didn't. I also thought about putting it in each of my view controllers viewWillAppear method and that didn't work.

Any idea on where to put this code?

Upvotes: 3

Views: 2829

Answers (3)

Bharat Modi
Bharat Modi

Reputation: 4178

What i have done for my case was, i have put below snippet in the didFinishLaunchingWithOptions

// Instantiate Shared Manager
[AFNetworkReachabilityManager sharedManager];

// Start network networking monitoring
[[AFNetworkReachabilityManager sharedManager] startMonitoring];

[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));


    if ([[AFNetworkReachabilityManager sharedManager] isReachable]) {
        NSLog(@"IS REACHABILE");

        //Here check if your network connection view is already showing on screen, if positive then remove it
        if (_viewNetworkConnectionCheck) {
          //[_viewNetworkConnectionCheck removeFromSuperView];  
           _viewNetworkConnectionCheck = nil;
        }
    } else {

        NSLog(@"NOT REACHABLE");

        //You have to add your network connectivity view here, just make sure if has been has not been allowcated
        if (!_viewNetworkConnectionCheck) {

            //[[UIApplication sharedApplication].keyWindow addSubview:_viewNetworkConnectionCheck];
        }
    }
}];

Also if you have to call web service every time app goes from background state to foreground state then what you can do is (or what i have done was) put below snippet in the delegate applicationWillEnterForeground

[self performSelector:@selector(callWebserviceToRefreshData) withObject:nil afterDelay:0.5f];

and add this method to call web service after checking internet connectivity safely

 -(void)callWebserviceToRefreshData {

      if ([JeebleyHelper isConnected]) {
         NSLog(@"Yes, network available");
         //Call your web service here
      } else {
         NSLog(@"No, network not available");
      }
}

Just make sure you call your dataRefresh method after some time delay, otherwise isConnected will always give you the previous state.

+ (BOOL)isConnected {
     return [AFNetworkReachabilityManager sharedManager].reachable;
}

Upvotes: 1

tgyhlsb
tgyhlsb

Reputation: 1915

If you plan to use network connections, you should take a look at AFNetworking https://github.com/AFNetworking/AFNetworking

The latest version of AFNetworking (2.0) is now built on top of NSURLSession, so you get all of the great features provided there. But you also get a lot of extra cool features – like serialization, reachability support, UIKit integration (such as a handy category on asynchronously loading images in a UIImageView), and more. It’s also one of the most widely used, open-source projects with over 10,000 stars, 2,600 forks, and 160 contributors on Github.

It has a feature called AFNetworkReachabilityManager to handle your request.

[[AFNetworkReachabilityManager sharedManager] startMonitoring];
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    DLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
    switch (status) {
        case AFNetworkReachabilityStatusReachableViaWWAN:
        case AFNetworkReachabilityStatusReachableViaWiFi:
            [operationQueue setSuspended:NO];
            NSLog(@"WIFI");
            break;
        case AFNetworkReachabilityStatusNotReachable:
        default:
            [operationQueue setSuspended:YES];
            NSLog(@"oflline");
            break;
    }
}];

You can find this code here

Upvotes: 5

GoodSp33d
GoodSp33d

Reputation: 6282

Ideally you should make a check for active internet connection before each network request.

But the link which you posted is only for detecting network state at that moment. You need to observe notifications instead which will let you know whenever net work state changed.

[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(networkStateChanged:)
                                                 name:kReachabilityChangedNotification object:nil];
Reachability *reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];

- (void)networkStateChanged:(NSNotification *)notice {
    NetworkStatus currentNetStatus = [reachability currentReachabilityStatus];
    if (currentNetStatus == NotReachable) {
        // No Internet connection
    } else {
        // We are back !
    }
}

This observer should be in your app delegate.

Upvotes: 2

Related Questions