Brandon
Brandon

Reputation: 2171

Run Internet Connection Check Throughout Entire App

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

Upvotes: 2

Views: 1020

Answers (3)

K'Prime
K'Prime

Reputation: 98

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

Upvotes: 0

GetSwifty
GetSwifty

Reputation: 7756

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

Upvotes: 1

Elliott
Elliott

Reputation: 4628

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

Upvotes: 3

Related Questions