2

The method below works very well for checking to see if a user has an internet connection. I would like to check for an internet connection throughout my entire app, and am wondering if there is somewhere I can put it within my App Delegate where it will get called from every view controller.

Is there a way to do this? Doesn't seem to work properly if I put it in my applicationDidFinishLaunching. Any recommendations would be great! Thank you!

NSURL *scriptUrl = [NSURL URLWithString:@"http://www.google.com/m"];
NSData *data = [NSData dataWithContentsOfURL:scriptUrl];
if (data) {
    NSLog(@"Device is connected to the internet");
}
else {
    NSLog(@"Device is not connected to the internet");
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Internet Connectivity" 
    message:@"You must have an internet connection" delegate:self cancelButtonTitle:@"OK" 
    otherButtonTitles:nil, nil];
    [alert show];
    return;
}
Brandon
  • 2,163
  • 6
  • 40
  • 64

3 Answers3

4

If you're looking to place this particular method in a location that can be accessed and called from the entirety of your application then this is simply a design decision. There are a number of ways to achieve this.

I like to make use of the singleton paradigm when implementing global methods. John Wordsworth covers this in a nice succinct blog post here:

http://www.johnwordsworth.com/2010/04/iphone-code-snippet-the-singleton-pattern/

Here's a quick chunk of code:

InternetConnectionChecker.h

#import <Foundation/Foundation.h>

@interface InternetConnectionChecker : NSObject

// Accessor for singelton instance of internet connection checker.
+ (InternetConnectionChecker *)sharedInternetConnectionChecker;

// Check to see whether we have a connection to the internet. Returns YES or NO.
- (BOOL)connected;

@end

InternetConnectionChecker.m

#import "InternetConnectionChecker.h"

@implementation InternetConnectionChecker

// Accessor for singelton instance of internet connection checker.
+ (InternetConnectionChecker *)sharedInternetConnectionChecker
{
    static InternetConnectionChecker *sharedInternetConnectionChecker;
    @synchronized(self)
    {
        if (!sharedInternetConnectionChecker) {
            sharedInternetConnectionChecker = [[InternetConnectionChecker alloc] init];
        }
    }
    return sharedInternetConnectionChecker;
}

// Check to see whether we have a connection to the internet. Returns YES or NO.
- (BOOL)connected
{
    NSURL *scriptUrl = [NSURL URLWithString:@"http://www.google.com/m"];
    NSData *data = [NSData dataWithContentsOfURL:scriptUrl];
    if (data) {
        NSLog(@"Device is connected to the internet");
        return TRUE;
    }
    else {
        NSLog(@"Device is not connected to the internet");
        return FALSE;
    }
}

@end

In my example I've amended your method to return a true/false so you can handle the result within the UI calling the method appropriately but you could continue to show a UIAlertView if you pleased.

You would then use the singleton in the following way:

InternetConnectionChecker *checker = [InternetConnectionChecker sharedInternetConnectionChecker];
BOOL connected = [checker connected];
Elliott
  • 4,598
  • 1
  • 24
  • 39
  • Thank you Elliott! This is awesome! So in my view controllers, do I need to do #import "InternetConnectionChecker.h"? What would a viewController look like to pull this all together? – Brandon Mar 03 '13 at 01:33
  • That's exactly right. After the import the two lines: `InternetConnectionChecker *checker = [InternetConnectionChecker sharedInternetConnectionChecker]; BOOL connected = [checker connected];` should be sufficient to call your method. – Elliott Mar 03 '13 at 01:35
  • Great, then I can just do if (connected == TRUE) { ... } yes? – Brandon Mar 03 '13 at 01:40
1

There are of course more complex ways of doing it, but the easiest way, (and the way I use) is to simply create a "CheckNetwork" class with your method as a class method which returns a bool, i.e:

+ (BOOL) checkConnection{
   yourMethodDetails;
}

then simply #import "CheckNetwork.h" into any file in your project and call

if([CheckNetwork checkConnection]){
    whatever you want to do here;
}
GetSwifty
  • 7,568
  • 1
  • 29
  • 46
0

While Singleton class and Static methods are a way, you could also implement static inline methods in a .h file which as no .m file

Also, as a sidetalk, checking internet connectivity using using NSURL along with google.com is not a good practice.

Because,

  • It is not a simple ping operation
  • It downloads the whole page which may consume time
  • OS provided ways are more radical and appropriate.

It you are working with a specific web site, then using that web site for connectivity is the best practice, i think. See this Answer by Jon Skeet

I would suggest using the Reachability framework by Apple.

Or if you need more compact single function version, you could also use this function excerpted from Reachabilty myself

+ (BOOL) reachabilityForInternetConnection;
{
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;

    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);

    SCNetworkReachabilityFlags flags;
    if (SCNetworkReachabilityGetFlags(reachability, &flags))
    {
        return (flags & kSCNetworkReachabilityFlagsConnectionRequired);
    }
    return NO;
}
Community
  • 1
  • 1
K'Prime
  • 98
  • 4