Search code examples
iosobjective-calert

Detect if there is no internet connection on iOS


I would like to make a "No Internet Connection Alert". Basically an alert that comes up if you have no Internet connection. I have tried using the Reachability but I didn't manage to figure anything out. Here's my view controller:

This is my .h file: P.S: My WebView is called 'webone'.

#import <UIKit/UIKit.h>

@interface FirstViewController : UIViewController

-(IBAction)refreshClicks:(id)sender;

@property (weak, nonatomic) IBOutlet UIWebView *webone;
@end

And This is My .m file:

#import "FirstViewController.h"
@interface FirstViewController ()

@end

@implementation FirstViewController
@synthesize webone;


-(void)viewDidLoad {
    NSURL *url = [NSURL URLWithString:@"http://www.lostcraft.net/mobile"]; 
    NSURLRequest *req = [NSURLRequest requestWithURL:url]; 
    [webone loadRequest:req];    
    [super viewDidLoad];
}

-(void)awakeFromNib{  //IGNORE
    [self refreshClicks:self]; //IGNORE
}

-(IBAction)refreshClicks:(id)sender{//IGNORE
    [webone loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.lostcraft.net/mobile"]]];//IGNORE
}

- (void)viewDidUnload
{
    [self setWebone:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}

Solution

  • Place this in your .m file

    Under Your IBAction:

    NSString *web = @"http://YOUR WEB ADRESS HERE";
                     NSURL *url = [NSURL URLWithString:web];
    NSURLRequest *requestUrl = [NSURLRequest requestWithURL:url];
    [webdone loadRequest:requestUrl];
    

    Then somewhere in your .m

    -(void)webView:(UIWebView *)webdone didFailLoadWithError:(NSError *)error {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Please check     your internet connection" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    
    }  
    

    go into connections tab in interface builder in xcode

    enter image description here

    Right click from the delegate as shown in the picture (the top option) and drag it to your view contoller where you have your web view (webdone)

    enter image description here