In this section, i will be describing about how we can check internet connectivity in iOS apps. For this kind of task, Apple has provided a very helpful sample reachability class . So, we will be using that class to make it working on our apps. First , grab the reachability sample code from: http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html
Now, you don't have to ho through all the codes in sample app, just follow these few steps to check internet connection in our app :
Now, you don't have to ho through all the codes in sample app, just follow these few steps to check internet connection in our app :
- Add the SystemConfiguration.framework to your project.
- Add the files Reachability.h and Reachability.m only from the Reachability sample code you just downloaded to your project.
- Add the following code in the implementation file where you need to test the Internet connection.
//// Just use it ,Where you need it (checking internet connection)
Reachability *reachTest = [Reachability reachabilityWithHostName:@"www.apple.com"];
NetworkStatus internetStatus = [reachTest currentReachabilityStatus];
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)){
/// Create an alert if connection doesn't work,no internet connection
UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"No Internet Connection"
message:@"You require an internet connection via WiFi or cellular
network for location finding to work." delegate:self
cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[myAlert show];
[myAlert release];
}
else{
// There is a internet connection
/// Do,Whatever you want
}
In case, if somehow www.apple.com is down you will find your self with no internet if you use
ReplyDeleteReachability *reachTest = [Reachability reachabilityWithHostName:@"www.apple.com"];
So it's better to use
Reachability *reachability = [Reachability reachabilityForInternetConnection];
Yes, thats gud one. Thats the beauty of the Reachability Class!!. What i wrote here for just Apple @"www.apple.com" is , i just set the example of which server we are going to connect (Apple in my case), So just checking weather a server i am trying to connect is reachable or not .
DeleteBut overall, Comment has been accepted!! Just use both, which suits on your project scenario . Thanx @rajan
This comment has been removed by the author.
ReplyDeleteIs this code compatible for ios 5 and later ? I am bulding a app that will support for ios 5 and later.
ReplyDeleteThank you.
Ofcourse it will work. This is small bunch of codes, why don't you try it !!!
DeleteThis comment has been removed by the author.
DeleteApple's documentation say it need runtime requirement ios 6 and later . please check look at this : https://developer.apple.com/library/ios/samplecode/Reachability/Introduction/Intro.html. I dont have a device to test ios 5.
DeleteThank you