So I make alert view detects if there in a active internet connection.
This is the Code:
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object:nil];
Reachability * reach = [Reachability reachabilityWithHostname:#"www.google.com"];
reach.reachableBlock = ^(Reachability * reachability)
{
dispatch_async(dispatch_get_main_queue(), ^{
blockLabel.text = #"";
});
};
reach.unreachableBlock = ^(Reachability * reachability)
{
dispatch_async(dispatch_get_main_queue(), ^{
blockLabel.text = #"You are not connected to the Internet";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Please connect to Internet"
message:nil
delegate:self
cancelButtonTitle:nil
otherButtonTitles:nil];
UIActivityIndicatorView *progress= [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(125, 50, 30, 30)];
progress.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
[alert addSubview:progress];
[progress startAnimating];
[alert show];
});
};
[reach startNotifier];
// Do any additional setup after loading the view, typically from a nib.
}
So my application detects if there is a internet connection. But the issue is that if I turn on internet on the iPhone and open the application it still saying there is not internet connection. What should I do…
Well i fix the issue by using notifications.. Code for Reference
-(void)reachabilityChanged:(NSNotification*)note
{
Reachability * reach = [note object];
if([reach isReachable])
{
notificationLabel.text = #"Notification Says Reachable";
NSLog(#"Internet is Up");
}
else
{
notificationLabel.text = #"Notification Says Unreachable";
NSLog(#"Internet is Down");
}
}
You could always implement a non-stop checking for host reachability (or internet connectivity) by signing up for reachability notifications.
One of best examples on how to do this can be found here on SO: How to check for an active Internet Connection on iPhone SDK?
This way your app will always know if the host is reachable or not.
There is no telling what your sparse code does as it does not even look like your Reachability class is Apple's Reachability sample code wrapper around the SystemConfiguration API , you can find that at http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html
The simplest and most definitive check is just a uncached NSURLRequest for a specific url (not just a hostname which merely tests if DNS resolution is working which is not a definitive test and could even be cached)
Related
I am trying to detect the internet is working or not on the device using AFNetworking ; referred to the answer here on the SO
AFNetworking 2.0 Reachability . I am able to detect device is connected with WiFi or 3G..
The problem is Actually internet is not working like the WIFI is on but internet is not working.
How Can i detect internet is working .Like we check using ping....
I am checking using the following
-(BOOL)connected {
__block BOOL reachable;
// Setting block doesn't means you area running it right now
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusNotReachable:
NSLog(#"No Internet Connection");
reachable = NO;
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
NSLog(#"WIFI");
reachable = YES;
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
NSLog(#"3G");
reachable = YES;
break;
default:
NSLog(#"Unkown network status");
reachable = NO;
break;
}
}];
// and now activate monitoring
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
return reachable;
}
Add notification observer for change in network status.
Like add following code in app delegate class under finish launching class
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(receiveNetworkChnageNotification:) name:AFNetworkingReachabilityDidChangeNotification object:nil];
Add global alertview in .h file. as it will appear and disappear on network status change.
here is notification function called on :
- (void)receiveNetworkChnageNotification:(NSNotification *)notification
{
if (![self isReachable])
{
self.alertView = [[UIAlertView alloc] initWithTitle:#"No Internet Connection" message:#"You have no internet connection on your device, please check and try again later." delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles:nil];
[self.alertView show];
}
else
{
[self.alertView dismissWithClickedButtonIndex:0 animated:YES];
}
}
You can use Reachability to determine if you have a functioning connection to a network. However if you really need to determine for some reason that you have a viable internet connection, then the best way is to attempt to establish an actual connection and examine the results. Use NSURLConnection for that.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.apple.com/"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSMutableData *receivedData = [NSMutableData dataWithCapacity:0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if(!theConnection) { // Something went wrong.
receivedData = nil;
}
To determine if you established a viable connection, examine the result of the connection using the the delegate method:
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Connection failed! Error - %# %#", [error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
I'm using AFNetworking to determine whether the user has an internet connection. It returns false on both wifi and 4G LTE and I have checked to make sure they're operational.
I have the following code:
-(void)viewDidLoad{
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
if ([self connected])
[self doSomething];
else
[self noConnection];
}
- (BOOL)connected {
NSLog(#"This returns 0 %hhd", [AFNetworkReachabilityManager sharedManager].reachable);
return [AFNetworkReachabilityManager sharedManager].reachable;
}
-(void)noConnection{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Internet!"
message:#"Sorry, but you don't have an internet connection at this time. Please try again later."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
This is not a solution using AFNetworking but using sample code from apple
Once you have downloaded and imported Reachbility.m and Reachbility.h files
create a helper function:
-(BOOL)isConnected{
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];
return !(networkStatus == NotReachable);
}
Then use it
if([self isConnected]){
//connected!
}
else{
//not connected to internet!
}
Very important
If your project is not using arc
go to target >
Build Phase >
double click the Reachability file
add -fno-objc-arc
Hope this helps
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
hi I’m trying check internet connection in my application. so for that i have already imported the reachability h file and m file in project. I’m getting some issues with that now. its working only if internet connection available its not working in without the net connection..
here this is the code which have used..
-(BOOL)reachable {
Reachability *reach = [Reachability reachabilityWithHostName:#"https://www.google.co.in/"];
NetworkStatus internetStatus = [reach currentReachabilityStatus];
if(internetStatus == NotReachable) {
UIAlertView *alertOne = [[UIAlertView alloc]initWithTitle:#"Internet" message:#"You dont have internet connection to send message" delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:#"ok", nil];
[alertOne show];
[alertOne release];
}
return YES;
}
i have already used this same code in other projects its working their but here its showing the alert message when internet connected its not showing when its not connected ...
this viewdidload code...
[super viewDidLoad];
[self reachable];
pls can any tell me how to resolve this...
thanks
Try below code
Reachability *reach = [Reachability reachabilityForInternetConnection];
//(or)
Reachability *reach = [Reachability reachabilityWithHostName:#"http://www.google.com"];
NetworkStatus netStatus = [reach currentReachabilityStatus];
if (netStatus != NotReachable)
{
//Reachable ..Network connection is available
}
else
{
//NSLog(#"Network Error No Network Available ");
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"" message:#"Please connect to an Internet connection to Register" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil , nil];
[alertView show];
}
It works for you...
This may not be the cause of the problem, but it is and always was wrong to call reachable in viewDidLoad. The reason is that viewDidLoad is way too early to call code that might put up an alert view. In viewDidLoad, your view is not even in the interface yet.
Another very odd thing is that your reachable method both detects reachability and puts up the alert. It returns a BOOL but you are throwing it away. You should be saying
if (![self reachable]) { // ...
and putting up the alert view there, not inside the reachable method.
Still another very weird thing is that your reachable method always returns YES. That's nuts. You should return YES if the URL is reachable and NO if it is not. Otherwise, what is the point of returning a BOOL at all?
Please follow this steps,
1>make property of Reachability and NetworkStatus;
in your appDelegate.h
#interface AppDelegate : UIResponder <UIApplicationDelegate,UITabBarControllerDelegate>{
Reachability* reachability;
NetworkStatus remoteHostStatus;
}
#end
2>Create Notification method when reachability changed in applicationDidBecomeActive
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object:nil];
reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];
remoteHostStatus = [reachability currentReachabilityStatus];
if(remoteHostStatus == NotReachable) {
if(DEBUG_MODE){NSLog(#"no");}
}
else if (remoteHostStatus == ReachableViaWiFi) {if(DEBUG_MODE)
{NSLog(#"wifi");}
}
else if (remoteHostStatus == ReachableViaWWAN) {if(DEBUG_MODE){NSLog(#"cell");}
}
}
3> declare reachabilityChanged
-(void)reachabilityChanged:(SCNetworkReachabilityFlags)flags
{
if([self isReachableWithFlags:flags])
{
if(self.reachableBlock)
{
self.reachableBlock(self);
}
}
else
{
if(self.unreachableBlock)
{
self.unreachableBlock(self);
}
}
// this makes sure the change notification happens on the MAIN THREAD
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:kReachabilityChangedNotification
object:self];
});
}
Thanks.
Hey guys i'm having a few problems with Apple's reachability code.
What i've found out is that, even if the device is correctly connected to the internet, initially the reachability code will send out 1 false notification(Networkstatus = NotReachable) followed by a couple of correct notifications (Networkstatus = ReachableViaWiFi).
Therefore, as i am displaying an UIAlertView when i get a "NotReachable" notification, even if the device is connected to the internet, the app still outputs an uialertview informing the user that the device is not connected.
Is there anyway to avoid this inconvenience?
Any help would be really appreciated.
This is my code:
In my .h file:
#property (nonatomic, retain) Reachability *hostReach;
In my .m file:
- (void)viewDidLoad
{
self.hostReach = [Reachability reachabilityWithHostname:#"www.google.com"];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
[_hostReach startNotifier];
NetworkStatus netStatus = [self.hostReach currentReachabilityStatus];
if(netStatus == NotReachable && _alertShowing==NO){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"No internet connection found"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
_alertShowing = YES;
[alert show];
}
...
}
-(void)reachabilityChanged:(NSNotification *)note {
Reachability* curReach = [note object];
NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
NetworkStatus netStatus = [curReach currentReachabilityStatus];
if(netStatus == NotReachable && _alertShowing==NO){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"No internet connection found"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
_alertShowing = YES;
[alert show];
}
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
_alertShowing = NO;
}
Why do you use reachabilityWithHostname:#"www.google.com"? This method checks the reachability of particular host (in your case google.com). And you receive notifications if Google available or not. Google may block you and you will receive NotReachable status.
Try to use:
//reachabilityForInternetConnection- checks whether the default route is available.
// Should be used by applications that do not connect to a particular host
+ (Reachability*) reachabilityForInternetConnection;
And also take a look on methods description here.
I would like to do some treatment when i loose connection, and when connection is back.
Are there any events to handle it ?
Thanks by advance,
E.
You should use good practices used in ASIHTTPRequest.
They use Reachability which is as they say a drop in replacement of the class develop by Apple
I hope it will help
One standard approach is to use Reachability to test network availability. It can be downloaded here. You only need Reachability.h and Reachability.m in your project.
My personal preference is to do the following -
1 Add the Reachability files
2 Create BOOL properties for each network test you wish to remember/expose in your project - I have a test for google and a test for google maps below.
3 In your appDidFinishLoading method call [self assertainNetworkReachability].
#pragma mark -
#pragma mark Reachability
-(void)assertainNetworkReachability {
[self performSelectorInBackground:#selector(backgroundReachabilityTests) withObject:nil];
}
-(void)backgroundReachabilityTests {
self.isInternetReachable = [self internetReachable];
self.isMapsReachable = [self mapsReachable];
self.connectivityTimer = [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:#selector(backgroundReachabilityTests) userInfo:nil repeats:NO];
}
-(BOOL)hostReachable:(NSString*)host {
Reachability *r = [Reachability reachabilityWithHostName:host];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if(internetStatus == NotReachable) {
[self throwNetworkDiagnosisAlert];
return NO;
}
return YES;
}
-(BOOL)internetReachable {
return [self hostReachable:#"www.google.co.uk"];
}
-(BOOL)mapsReachable {
return [self hostReachable:#"maps.google.com"];
}
-(BOOL)isInternetGoodYetMapsUnreachable {
return (self.isInternetReachable && !self.isMapsReachable);
}
-(void)throwNetworkDiagnosisAlert {
NSString* title = #"Connectivity Problem";
NSString* message = #"You are not connected to the internet.";
if (self.isInternetGoodYetMapsUnreachable) {
message = #"Unable to connect to the Google Maps server.";
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[alert show];
[alert release];
}