Check for Internet Connection in a UIWebView iPhone App

This is an important part of programming a UIWebView iPhone App, the App Store will turn down your app if you cannot check for internet connectivity!

The code below checks for Internet connectivity (from Wi-Fi AND wireless network), and if there is no connection, we throw a UIAlertView notification with a button that closes the app:

(note: we place this code in the viewController.m file)

//No Internet Connection error code
-(void)webView:(UIWebView *)myWebView didFailLoadWithError:(NSError *)error {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"You have no internet connection!" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil, nil];
    [alert show];

}

And then we can put this code in right below in order to close the app when the “Close” button is pressed:

//Close app from AlertView
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    exit(0);
}

And there we have it! This is a very important part of iPhone app development where you will be using the device’s internet! Feel free to ask any questions below!

A web and application developer, based in Chicago, IL. Founder of Dragon Fruit Development (www.dragonfruitdevelopment.com) More articles by Todd Dunham
  • For some reason, this didn’t work for me…
    And also, Apple strictly recommends not to use the exit() function,
    as they say this causes bugs…

Home CSS Deals HTML HTML5 Java JavaScript jQuery Miscellaneous Mobile MySQL News PHP Resources Security Snippet Tools Tutorial Web Development Web Services WordPress