 |
|
 |
|
 |
12-02-2008, 04:11 PM
|
#1 (permalink)
|
|
Registered Member
Join Date: Aug 2008
Location: Germany, Munich
Posts: 238
|
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
|
|
|
12-02-2008, 07:30 PM
|
#2 (permalink)
|
|
Registered Member
Join Date: Aug 2008
Location: Germany, Munich
Posts: 238
|
Solved it with a example from a book (i hate reading) :-)
|
|
|
12-02-2008, 07:49 PM
|
#3 (permalink)
|
|
Registered Member
Join Date: Jul 2008
Posts: 413
|
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.
|
|
|
12-02-2008, 08:00 PM
|
#4 (permalink)
|
|
Registered Member
Join Date: Aug 2008
Location: Germany, Munich
Posts: 238
|
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
|
|
|
12-02-2008, 08:28 PM
|
#5 (permalink)
|
|
New Member
Join Date: Sep 2008
Posts: 30
|
Quote:
Originally Posted by rhuettl
...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
|
|
|
12-02-2008, 09:06 PM
|
#6 (permalink)
|
|
Registered Member
Join Date: Sep 2008
Posts: 352
|
is that code the example from the book?
|
|
|
01-12-2009, 07:31 PM
|
#7 (permalink)
|
|
Registered Member
Join Date: Jun 2008
Posts: 92
|
when i try to implement this i get error's first one being storage size of zeroaddress isnt known, ideas?
|
|
|
01-12-2009, 10:39 PM
|
#8 (permalink)
|
|
Registered Member
Join Date: Dec 2008
Posts: 143
|
I got the same code out of a book and got the same error message as the poster above.
|
|
|
01-15-2009, 09:06 AM
|
#9 (permalink)
|
|
New Member
Join Date: Jan 2009
Posts: 8
|
Add the SystemConfiguration framework - also don't forget to
#import <SystemConfiguration/SCNetworkReachability.h>
#include <netinet/in.h>
|
|
|
01-15-2009, 02:01 PM
|
#10 (permalink)
|
|
Registered Member
Join Date: Dec 2008
Posts: 143
|
Ah, of course. That was dumb.
|
|
|
01-27-2009, 03:52 AM
|
#11 (permalink)
|
|
Ashar
Join Date: Aug 2008
Posts: 54
|
Hey
the code above doesn't detect cellular network. any idea on how to do that?
|
|
|
02-05-2009, 05:39 PM
|
#12 (permalink)
|
|
New Member
Join Date: Feb 2009
Posts: 2
|
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?
|
|
|
02-05-2009, 06:44 PM
|
#13 (permalink)
|
|
New Member
Join Date: Feb 2009
Posts: 2
|
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.
|
|
|
02-21-2009, 02:12 AM
|
#14 (permalink)
|
|
Mobile Application Dev.
Join Date: Oct 2008
Location: Bangalore, india
Posts: 262
|
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.
|
|
|
02-21-2009, 10:12 AM
|
#15 (permalink)
|
|
New Member
Join Date: Jan 2009
Posts: 8
|
zeroaddress
Quote:
Originally Posted by mpramodjain
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"]....
|
|
|
03-19-2009, 01:41 PM
|
#16 (permalink)
|
|
New Member
Join Date: Oct 2008
Posts: 22
|
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.
|
|
|
03-26-2009, 12:26 PM
|
#17 (permalink)
|
|
New Member
Join Date: Mar 2009
Posts: 15
|
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.
|
|
|
11-17-2009, 07:08 PM
|
#18 (permalink)
|
|
Registered Member
Join Date: Feb 2009
Posts: 16
|
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
|
|
|
11-18-2009, 04:31 AM
|
#19 (permalink)
|
|
Hot Cocoa Touch
Join Date: Oct 2009
Location: near the oil spill.
Posts: 136
|
Quote:
Originally Posted by wynodir
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
|
|
|
11-18-2009, 09:30 AM
|
#20 (permalink)
|
|
Tutorial Author
Join Date: Oct 2008
Location: Ontario, Canada
Posts: 460
|
Quote:
Originally Posted by redon
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.
|
|
|
12-15-2009, 09:44 AM
|
#21 (permalink)
|
|
Registered Member
Join Date: Aug 2009
Posts: 51
|
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
|
|
|
01-26-2010, 09:18 AM
|
#22 (permalink)
|
|
iPod Touch 8GB
Join Date: Oct 2009
Location: MY
Age: 32
Posts: 1,604
|
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."
|
|
|
01-26-2010, 12:40 PM
|
#23 (permalink)
|
|
iPhone SDK fanatics!
Join Date: Aug 2009
Location: Malaysia
Posts: 272
|
Quote:
Originally Posted by rhuettl
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)webViewDidStartLoad  UIWebView *)webView
{
// starting the load, show the activity indicator in the status bar
[myActivityIndicatorView startAnimating];
}
- (void)webViewDidFinishLoad  UIWebView *)webView
{
[myActivityIndicatorView stopAnimating];
}
- (void)webView  UIWebView *)webView didFailLoadWithError  NSError *)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!
|
|
|
01-26-2010, 01:21 PM
|
#24 (permalink)
|
|
iPod Touch 8GB
Join Date: Oct 2009
Location: MY
Age: 32
Posts: 1,604
|
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."
|
|
|
01-27-2010, 04:27 AM
|
#25 (permalink)
|
|
Registered Member
Join Date: Aug 2009
Posts: 51
|
Quote:
Originally Posted by rocotilos
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
|
|
|
 |
|
| Thread Tools |
|
|
| Display Modes |
Linear Mode
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|
» Advertisements |
» Online Users: 394 |
| 30 members and 364 guests |
| AdamSubach, aderrington, airsoft808, benoitr007, bensj, BrianSlick, Danneman, dev123, ErichGS, gtyt38, gustavo7sexton, HemiMG, Jeremy1026, lifeCoder45, mriphoneman, Ovidius, Paul10, Piequanna, pofak, qilin, Racker, raheel, Sega dude, socals, squidboy, timle8n1, ZunePod |
| Most users ever online was 965, 06-30-2010 at 04:26 AM. |
» Stats |
Members: 41,860
Threads: 49,768
Posts: 213,054
Top Poster: BrianSlick (3,138)
|
| Welcome to our newest member, gustavo7sexton |
|