Advertise Books Events Forum News Social Networking Support Us
Follow @iphonedevsdk on Twitter

sdkIQ for iPhone
($4.99)

Your First iPhone App
($1.99)

iPhone Code Generator
($9.99)

Dual Matches
($0.99)

Calcuccino Programmers' Calculator
($2.99)

SDKtoday
(free)

Want your application or service advertised on iPhone Dev SDK?

Go Back   iPhone Dev SDK Forum > iPhone SDK Development Forums > iPhone SDK Development

Reply
 
LinkBack Thread Tools Display Modes
Old 12-02-2008, 04:11 PM   #1 (permalink)
Registered Member
 
Join Date: Aug 2008
Location: Germany, Munich
Posts: 238
Default Test if internet connection is available

Hi there,

is there a simple piece of code testing if the internet is available on the iPhone - i know the reachability example app but that seems to be a great overhead. So i only like a network test (CFNetwork ?) who can check this - any help available?

Cheers :-)
Ralf
rhuettl is offline   Reply With Quote
Old 12-02-2008, 07:30 PM   #2 (permalink)
Registered Member
 
Join Date: Aug 2008
Location: Germany, Munich
Posts: 238
Default

Solved it with a example from a book (i hate reading) :-)
rhuettl is offline   Reply With Quote
Old 12-02-2008, 07:49 PM   #3 (permalink)
Registered Member
 
Join Date: Jul 2008
Posts: 413
Default

There is another way for testing network availability. I have to admit, it's not the nicest one :-)

You could use a hidden UIWebView and load a website to it. Then use methods from the UIWebView.h to detect, whether loading was successful or not.
NewiPhoneDeveloper is offline   Reply With Quote
Old 12-02-2008, 08:00 PM   #4 (permalink)
Registered Member
 
Join Date: Aug 2008
Location: Germany, Munich
Posts: 238
Default

Hi,

hmm that sounds a bit crazy :-)

Here is the code (tested and working fine):

Code:
- (BOOL) connectedToNetwork
{
    // Create zero addy
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
	
    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
	
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
	
    if (!didRetrieveFlags)
    {
        printf("Error. Could not recover network reachability flags\n");
        return 0;
    }
	
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    return (isReachable && !needsConnection) ? YES : NO;
}
Ciao
Ralf
rhuettl is offline   Reply With Quote
Old 12-02-2008, 08:28 PM   #5 (permalink)
New Member
 
Join Date: Sep 2008
Posts: 30
Default

Quote:
Originally Posted by rhuettl View Post
...is there a simple piece of code testing if the internet is available...
Hi Ralf,

What if your iPhone connects to a wireless router, and that router is not connected to the internet? Will your app fail gracefully?

-peace
backwardselvis is offline   Reply With Quote
Old 12-02-2008, 09:06 PM   #6 (permalink)
Registered Member
 
Join Date: Sep 2008
Posts: 352
Default

is that code the example from the book?
erotsppa is offline   Reply With Quote
Old 01-12-2009, 07:31 PM   #7 (permalink)
Registered Member
 
Join Date: Jun 2008
Posts: 92
Default

when i try to implement this i get error's first one being storage size of zeroaddress isnt known, ideas?
nownot is offline   Reply With Quote
Old 01-12-2009, 10:39 PM   #8 (permalink)
Registered Member
 
Join Date: Dec 2008
Posts: 143
Default

I got the same code out of a book and got the same error message as the poster above.
ambiensignal is offline   Reply With Quote
Old 01-15-2009, 09:06 AM   #9 (permalink)
New Member
 
Join Date: Jan 2009
Posts: 8
Default

Add the SystemConfiguration framework - also don't forget to
#import <SystemConfiguration/SCNetworkReachability.h>
#include <netinet/in.h>
dbrownstone is offline   Reply With Quote
Old 01-15-2009, 02:01 PM   #10 (permalink)
Registered Member
 
Join Date: Dec 2008
Posts: 143
Default

Ah, of course. That was dumb.
ambiensignal is offline   Reply With Quote
Old 01-27-2009, 03:52 AM   #11 (permalink)
ash
Ashar
 
Join Date: Aug 2008
Posts: 54
Default

Hey

the code above doesn't detect cellular network. any idea on how to do that?
__________________
--
Ashar
www.tkxel.com
ash is offline   Reply With Quote
Old 02-05-2009, 05:39 PM   #12 (permalink)
New Member
 
Join Date: Feb 2009
Posts: 2
Default

It seems there is a bit of an issue with the above code and it may need to be modified depending upon your intended use. I put this code into my app (original code provided by Apple; thank you Apple) and it only worked when the iPhone was on a WiFi connection. I did some research and testing to come up with a solution.
There are a set of flags that can be used to determine connectivity (iPhone Dev Center). Not being entirely sure which to use, I set up a tester that would show me which flags are active when I am using different connection methods. This is something that I would recommend anyone to try so that you can get a better understanding of how it works, however this is the change I made that seemed to fix the issue:

Code:
...
    isReachable = flags & kSCNetworkFlagsReachable;
    needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    nonWiFi = flags & kSCNetworkReachabilityFlagsTransientConnection;

 return ((isReachable && !needsConnection) || nonWiFi) ? YES : NO;
...
If someone knows a better way or if im completely wrong here, please let me know.
The problem I am trying to research now is that once the iPhone has left the WiFi connection and gone on to the 3G or Edge networks, it wont go back onto the WiFi again even if I am in range of the signal. I have to exit my app and either wait or reinitialize it in the settings. Does anyone know a way around this?
Bungler is offline   Reply With Quote
Old 02-05-2009, 06:44 PM   #13 (permalink)
New Member
 
Join Date: Feb 2009
Posts: 2
Default

OK, I think I have resolved the issue above with some research on this forum. I changed the last IF statement to the following:

Code:
...
return ((isReachable && !needsConnection) || nonWiFi) ? 
(([[NSURLConnection alloc] initWithRequest:[NSURLRequest 
requestWithURL: [NSURL URLWithString:@"http://www.apple.com/"] 
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0] 
delegate:self]) ? YES : NO) : NO;
...
What (I think) its doing is after it tests for reachability, it requests data from a www site using NSURLConnection, which makes the iPhone search for connections. Sorry for my non-technical explanations


EDIT: I changed the cache policy to not pull from the local cache so that it looks for the page every time. In my code, I also am not using apple.com as the request URL. I put up a simple html page on my server with the word 'true' in it and I am requesting that page for the connection testing. Keeping the request small might help the load time, even if you are doing nothing with the requested data. Even a 404 returns something.

Last edited by Bungler; 02-05-2009 at 07:14 PM.
Bungler is offline   Reply With Quote
Old 02-21-2009, 02:12 AM   #14 (permalink)
Mobile Application Dev.
 
Join Date: Oct 2008
Location: Bangalore, india
Posts: 262
Default

Hi all,

This is very very good thread ,,atmost usefulllll..
but unable to understand , what does the zeroaddress contains..Any link on web would be help ful for understanding this..
Thank u all.

Last edited by mpramodjain; 02-21-2009 at 02:36 AM.
mpramodjain is offline   Reply With Quote
Old 02-21-2009, 10:12 AM   #15 (permalink)
New Member
 
Join Date: Jan 2009
Posts: 8
Default zeroaddress

Quote:
Originally Posted by mpramodjain View Post
Hi all,

This is very very good thread ,,atmost usefulllll..
but unable to understand , what does the zeroaddress contains..Any link on web would be help ful for understanding this..
Thank u all.
The zero address is simply 0.0.0.0 - I in fact, chose to use apple.com to check for connectivity ...[self hostAvailable:@"www.apple.com"]....
dbrownstone is offline   Reply With Quote
Old 03-19-2009, 01:41 PM   #16 (permalink)
New Member
 
Join Date: Oct 2008
Posts: 22
Default

If the code in any case connects to a web server to try if there's a connection, why not just do this:

Code:
- (BOOL) connectedToNetwork
{
   return ([NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.myserver.com/smalltext.txt"]]!=NULL)?YES:NO;
}
This function will return NO if it cannot reach the file. Otherwise, it will return YES. I tried it in flight mode and in 3G mode. It works.
wynodir is offline   Reply With Quote
Old 03-26-2009, 12:26 PM   #17 (permalink)
New Member
 
Join Date: Mar 2009
Posts: 15
Default

Wynodir: How does ur suggestion handle timeouts?

I tested it this way but my application will just wait and wait and wait and wait... I need to set a timeout. Can u tell me how?

EDIT: What datatype is this nonWifi?

Last edited by Ben.; 03-26-2009 at 12:31 PM.
Ben. is offline   Reply With Quote
Old 11-17-2009, 07:08 PM   #18 (permalink)
Registered Member
 
Join Date: Feb 2009
Posts: 16
Default

The Reachability sample code is what you should be looking at here. Although the class it uses is almost 1000 lines long, it shows you how it all works. I'm about to start picking through it all for what I need
sirjec is offline   Reply With Quote
Old 11-18-2009, 04:31 AM   #19 (permalink)
Hot Cocoa Touch
 
redon's Avatar
 
Join Date: Oct 2009
Location: near the oil spill.
Posts: 136
Default

Quote:
Originally Posted by wynodir View Post
If the code in any case connects to a web server to try if there's a connection, why not just do this:

Code:
- (BOOL) connectedToNetwork
{
   return ([NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.myserver.com/smalltext.txt"]]!=NULL)?YES:NO;
}
This function will return NO if it cannot reach the file. Otherwise, it will return YES. I tried it in flight mode and in 3G mode. It works.
i tryed the following code, put my iphone in airplane mode and ran the app. it appears to not work...at all


Code:
- (BOOL) connectedToNetwork {
	return ([NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.apple.com/"]]!=NULL)?YES:NO;
	
	if (YES) {
	}
	
	if (NO) {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"no internet connection" 
													   delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
	    [alert release];
	}
}
__________________
Love always,

Orly Owl
redon is offline   Reply With Quote
Old 11-18-2009, 09:30 AM   #20 (permalink)
Tutorial Author
 
Steaps's Avatar
 
Join Date: Oct 2008
Location: Ontario, Canada
Posts: 460
Default

Quote:
Originally Posted by redon View Post
i tryed the following code, put my iphone in airplane mode and ran the app. it appears to not work...at all


Code:
- (BOOL) connectedToNetwork {
	return ([NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.apple.com/"]]!=NULL)?YES:NO;
	
	if (YES) {
	}
	
	if (NO) {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"no internet connection" 
													   delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
	    [alert release];
	}
}
Nothing after the return statement is being called. Try using NSLog() to see where code ends/if it's called.
Steaps is offline   Reply With Quote
Old 12-15-2009, 09:44 AM   #21 (permalink)
Registered Member
 
Join Date: Aug 2009
Posts: 51
Default

I like the idea of loading a small string from the web. I tested it on the simulator and the following code works fine if my internet is connected or not connected. I gave it a 2 second timeout...

Code:
-(void)viewDidAppear:(BOOL)animated {
	NSString *connected = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.mysite.com/smallfile.php"]];
	wait(20000);
	if (connected == NULL) {
		NSLog(@"Not connected");
	} else {
		NSLog(@"Connected - %@",connected);
	}
}
EDIT: Tested it on the device as part of a much bigger app. Works as expected in flight mode / normal connection. If you want to increase the timeout perhaps it might be worth it, but it's working fine for me!

Last edited by ziophase; 12-15-2009 at 10:06 AM. Reason: more info available
ziophase is offline   Reply With Quote
Old 01-26-2010, 09:18 AM   #22 (permalink)
iPod Touch 8GB
 
rocotilos's Avatar
 
Join Date: Oct 2009
Location: MY
Age: 32
Posts: 1,604
Default

Holy cow! You guys are awesome.
Thanks for the code ziophase.
__________________

New & Noteworthy Apr '10
(click icon.. it's a FREE App!)

"...I decided that Apple can't afford to change its core values and simply let it slide. We have the same core values as when we started, and we come into work wanting to do the same thing today that we wanted to do five years ago."
rocotilos is offline   Reply With Quote
Old 01-26-2010, 12:40 PM   #23 (permalink)
iPhone SDK fanatics!
 
Join Date: Aug 2009
Location: Malaysia
Posts: 272
Default

Quote:
Originally Posted by rhuettl View Post
Hi there,

is there a simple piece of code testing if the internet is available on the iPhone - i know the reachability example app but that seems to be a great overhead. So i only like a network test (CFNetwork ?) who can check this - any help available?

Cheers :-)
Ralf

Two methods I tried. Reachability is still the best for me. It detect even changes from WifI to 3G to EDGE, etc...

Easier to use method is the UIWebView protocol itself. Hope the code below helps.

#pragma mark UIWebView delegate methods

- (void)webViewDidStartLoadUIWebView *)webView
{
// starting the load, show the activity indicator in the status bar
[myActivityIndicatorView startAnimating];
}

- (void)webViewDidFinishLoadUIWebView *)webView
{
[myActivityIndicatorView stopAnimating];
}

- (void)webViewUIWebView *)webView didFailLoadWithErrorNSError *)error
{
int myErrorCode;

[myActivityIndicatorView stopAnimating];

myErrorCode = [error code]; // myErrorCode = -999 if user cancel action, not network problem
if (ckErrorCode != -999)
{
// Your error handling code here
NSLog(@"UIWebView Load Failed-Error");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Connection Error!" message:@"Unable to connect to the website." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
[alert show];
}
}

// #pragma mark UIWebView delegate methods
__________________
KennyChong
iPhone SDK Fanatic!
KennyChong is offline   Reply With Quote
Old 01-26-2010, 01:21 PM   #24 (permalink)
iPod Touch 8GB
 
rocotilos's Avatar
 
Join Date: Oct 2009
Location: MY
Age: 32
Posts: 1,604
Default

Whoa KennyChong, Another fellow countryman.
__________________

New & Noteworthy Apr '10
(click icon.. it's a FREE App!)

"...I decided that Apple can't afford to change its core values and simply let it slide. We have the same core values as when we started, and we come into work wanting to do the same thing today that we wanted to do five years ago."
rocotilos is offline   Reply With Quote
Old 01-27-2010, 04:27 AM   #25 (permalink)
Registered Member
 
Join Date: Aug 2009
Posts: 51
Default

Quote:
Originally Posted by rocotilos View Post
Holy cow! You guys are awesome.
Thanks for the code ziophase.

There's a much better way to do it!

Download the apple sample code reachability.

Then follow the steps listed in post 29 here:

No WIFI connection - best practice?

Cheerio
ziophase is offline   Reply With Quote
Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


» Advertisements
» Stats
Members: 41,860
Threads: 49,768
Posts: 213,054
Top Poster: BrianSlick (3,138)
Welcome to our newest member, gustavo7sexton
Powered by vBadvanced CMPS v3.1.0

All times are GMT -5. The time now is 06:58 PM.
Powered by vBulletin® Version 3.8.0
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.2.0