Checking if there is an active internet connection iPhone situation
I would like to check to see if the user has an active internet connection. This is how I have implemented it. It seems to work fine but the problem is it ALWAYS shows that there is no connection on my iPhone simulator (uialert comes up) even when my wifi is turned on or off. Does any know what I am doing wrong? Thanks for your help!
Reachability *r= [Reachability reachabilityWithHostName:@"http://www.google.com"];
NetworkStatus internetStatus= [r currentReachabilityStatus];
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
{
UIAlertView *alert= [[UIAlertView alloc开发者_运维知识库] initWithTitle:@"No internet" message:@"No internet connection found. Please try again later"
delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
else {
// execute code in app
}
This is how I have done it in my apps:
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus internetStatus = [reachability currentReachabilityStatus];
if(internetStatus == NotReachable) {
UIAlertView *errorView;
errorView = [[UIAlertView alloc]
initWithTitle: NSLocalizedString(@"Network error", @"Network error")
message: NSLocalizedString(@"No internet connection found, this application requires an internet connection to gather the data required.", @"Network error")
delegate: self
cancelButtonTitle: NSLocalizedString(@"Close", @"Network error") otherButtonTitles: nil];
[errorView show];
[errorView autorelease];
}
What is does is that it checks for an internetconnection, not if it can reach a domain. If no internet connection (wifi or celluar) it will show an UIAlertView message (localized).
Don't check. The radio often starts turning on and establishing a connection just after reachability reports no network (the reachability reporting that there is no network may be what starts this process and thus renders it's own answer to be false a few seconds later.)
精彩评论