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.)
Related
This web view failed error showing the alert popup even when it is loading the website. I believe I need to delay this method in order for it to work.What will be the best method for doing this?
- (void)webView:(UIWebView *)webViewfail didFailLoadWithError:(NSError *)error
{
if([webViewfail isEqual:webview]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Connection Failed" message:#"Check your Internet connection before refreshing."
delegate:webview
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
Here is how I am loading the website
- (void)viewDidLoad
{
[webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.blabla.com"]]];
}
The problem is most likely an error -999 which generally happens when something from the webpage does not load correctly or a user tries to navigate back while the page is still loading. After some research here's what I found and used to keep the NetworkAlert from poping up every time but still popping up when there is no network.
-(void)webView:(UIWebView *)webBlog didFailLoadWithError:(NSError *)error{
if ([error code] != -999) {
NSLog(#"Could not load the dumb webPage");
//show error alert, etc.
[self showNoNetworkAlert];
}else{
NSLog(#"Could not load the dumb web page...just might blame user!");
}
}
- (void) showNoNetworkAlert{
UIAlertView *baseAlert = [[UIAlertView alloc]
initWithTitle:#"No Network" message:#"A network connection is required. Please verify your network settings and try again."
delegate:nil cancelButtonTitle:nil
otherButtonTitles:#"Dismiss", nil];
[baseAlert show];
}
Hope this helps someone...
Looking for some help again...
I've currently got 2 sections of my app that need internet connection, 1 is a photo gallery through Flickr and the other a Twitter Feed, I was wondering if this is the correct code for the UIAlertView... I can get it working from a button but thats all!
{
-(void)didTap_roundedRectButton1:(id)sender forEvent:(UIEvent *)event {
UIAlertView *alertView = [[UIAlertView alloc] init];
alertView.title = #"You are not connected to the Internet!";
alertView.message = #"Please check your connection and try again...";
[alertView addButtonWithTitle:#"Ok"];
[alertView show];
[alertView release];
}
i think you need to use this example as i have used it to check is there any network is available and device is connected to any one of the network it is alos available on the apple's developer example site
example link is this
You should try this:
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"You are not connected to the Internet!"
message:#"Please check your connection and try again..."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alertView show];
[alertView release];
and can you post the code how do you create the UIButton?
I'm getting false positives with my Reachability code. I get the UIAlert "No Internet Connection", when the network is available but not activated. Any help is very much appreciated.
//Check for Internet
Reachability* wifiReach = [[Reachability reachabilityWithHostName: #"www.apple.com"] retain];
NetworkStatus netStatus = [wifiReach currentReachabilityStatus];
switch (netStatus)
{
case NotReachable:
{
NSLog(#"Access Not Available");
break;
}
case ReachableViaWWAN:
{
NSLog(#"Reachable WWAN");
break;
}
case ReachableViaWiFi:
{
NSLog(#"Reachable WiFi");
break;
}
}
if (netStatus==NotReachable){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Internet Required" message:#"There is no internet connection. Please connect and try again" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
[alert release];
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}else{
//Push Controller
}
Same answer as the previous question.
Reachability sometimes only gives the correct answer after your app, or some previous app, has tried to connect and waited for data. So you might as well just try to get data from your connection, as that may well give you a more correct answer more quickly than asking the Reachability API. Maybe just let the user decide an activity indicator has been spinning long enough.
this code is to check if internet connection is available or not.If internet connection is available then username and password should get validated from server database i.e send request method should get called and if not then username and password should get validated from local database i.e check method should get called.but the prob here is when the internet is off then also it gets into the send request method instead of getting in check nethod.What may be the prob.Please help me in solving this problem. i have added reachability files and imported the CFNetwork.framework.
- (void) showNetWorkAlert {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
UIAlertView *networkAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Network connection unavailable."
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:#"Retry", nil];
[networkAlert show];
[networkAlert release];
}
#pragma mark To Check Network Connection.
- (BOOL) currentNetworkStatus {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
BOOL connected;
const char *host = "www.apple.com";
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, host);
SCNetworkReachabilityFlags flags;
connected = SCNetworkReachabilityGetFlags(reachability, &flags);
BOOL isConnected = YES;
isConnected = connected && (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired);
CFRelease(reachability);
if(!isConnected) {
// sleep(1);
[self showNetWorkAlert];
//[self check];
}
else
return isConnected;
//[self sendRequest];
return isConnected;
}
-(IBAction)buttonPressed:(id)sender
{
//[self sendRequest];
//[[Reachability sharedReachability] setHostName:kHostName];
//Set Reachability class to notifiy app when the network status changes.
//[[Reachability sharedReachability] setNetworkStatusNotificationsEnabled:YES];
//Set a method to be called when a notification is sent.
//[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(reachabilityChanged:) name:#"kNetworkReachabilityChangedNotification" object:nil];
//[self updateStatus];
//[self sendRequest];
//NSLog(<#NSString *format#>)
//this is to select username and password from database.
//[self check];
if ([self currentNetworkStatus]) {
[self sendRequest];
}
else {
[self check];
}
}
Rocky your code is right .Just check the URL is proper or not .
there is other way also
On button check the host like this
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object:nil];
hostReach = [[Reachability reachabilityWithHostName:#"www.google.com"]retain];
[hostReach startNotifier];
and in the (reachabilityChanged:) method call make like this
-(void)reachabilityChanged:(NSNotification*)note
{
static BOOL showNotConnnected =NO;
Reachability *curReach =[note object];
NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
NetworkStatus netStatus = [curReach currentReachabilityStatus];
if(netStatus != NotReachable)
{
UIAlertView *notconnect1 = [[UIAlertView alloc]initWithTitle:#"Server is connected" message:#"Server is connected" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:#"Cancel",nil];
[notconnect1 show];
[notconnect1 release];
}
else if(showNotConnnected == NO)
{
showNotConnnected =YES;
UIAlertView *notconnect = [[UIAlertView alloc]initWithTitle:#"Server is Not connected" message:#"Server may be slow or not connected" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:#"Cancel",nil];
[notconnect show];
[notconnect release];
}
}
I hope this will help you
I do think there is a sample code called Reachability from apple can help you. see the URL below
http://developer.apple.com/library/ios/samplecode/Reachability/Introduction/Intro.html
You should look at Apple's reachability code to check for a connection to the Internet. There is a sample project you can get from them in the iOS Developer Portal.
Reachability should not be used to detect if the network is available before making a network request because the act of making a network request can bring up the network if needed. Reachability should only be used to detect when the network becomes available after being unavailable.
Just try making the network request -- you'll get an error back if the network is unavailable. Usually the response will come back right away, but if the network is spotty it can take a while, so you shouldn't ever make synchronous network calls on the main thread. Use NSURLConnection if possible and you'll get callbacks when something happens.
When you first try to access a user's ALAssetsLibrary, the OS will present them with a dialog asking for permission. If they do not allow this, a failureBlock will be called and will always be called in the future. Is there a way to force a prompt of this authorization request again?
I notice in the Maps app, that they inform the user to go to the Settings app to turn on location services with a button. However, there is no way that I know of to programmatically open the Settings app. Should I just display directions as to how to turn on the location services?
You can't open up the settings app in an Apple approved manner.
The best you can hope for is to trap the error and then display a UIAlertView or other view with instructions on how to do this. Take a look at the latest v. of the Dropbox app for an idea on how they instruct the user.
When you try to access the Library from your code, you can use the error handler to catch the error and display an alert specifying to the user what to do.
Example
failureBlock:^(NSError *error) {
// error handling
if (error.code == ALAssetsLibraryAccessGloballyDeniedError) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error!"
message:#"Error loading image... \nEnable Location Services in 'Settings -> Location Services'."
delegate:self cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alert show];
} else if (error.code == ALAssetsLibraryAccessUserDeniedError) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error!"
message:[NSString stringWithFormat:#"Error loading image... \nEnable Location Services in 'Settings -> Location Services' for %#.", [[[NSBundle mainBundle] infoDictionary] objectForKey:#"CFBundleDisplayName"]]
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error!" message:#"Error loading image..." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
}