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]);
}
Related
I am new in ios. i have develop a practice app, where i use rechability for network connection. but i have problem in that, when network is weak it shows the 'No network' message.
but i want in weak signal, it should access the internet within a 30sec timeout interval.
How Can i access the internet in weak signal within timeout interval.
I have tried the following:
-(BOOL)getInternetConnectionStatus
{
Reachability *objReachability = [Reachability reachabilityWithHostName:#"www.google.com"];
NetworkStatus internetStatus = [objReachability currentReachabilityStatus];
BOOL boolInternet;
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
{
boolInternet = NO;
}
else
{
boolInternet = YES;
}
return boolInternet;
}
-(IBAction)buttonClick:(id)sender
{
// call web service
if (![self getInternetConnectionStatus])
{
UIAlertView *alertMessage=[[UIAlertView alloc]initWithTitle:#"Alert" message:#"No Internet Connection" delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alertMessage show];
return;
}
else
{
NSData *dataReply;
NSURLResponse *response;
NSError *error;
// create the request
NSString *urlString = [NSString stringWithFormat:#"http://Your link" ];
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:0.3];
// Make the connection
dataReply = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
if (response != nil)
{
NSLog(#"SNNetworkController.isHostAvailable %#", response);
UIAlertView *alertMessage=[[UIAlertView alloc]initWithTitle:#"Alert" message:#"Wel-Come" delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alertMessage show];
}
else
{
// inform the user that the download could not be made
NSLog(#"SNNetworkController.isHostAvailable %# %#", response, error);
UIAlertView *alertMessage=[[UIAlertView alloc]initWithTitle:#"Alert" message:#"No Internet Connection" delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alertMessage show];
}
}
}
But it shows the message 'No Internet Connection' when signal is weak.
how can i shows the 'Wel-come' message within timeout when signal is weak.
Please give me the answer....
Thanks in advanced....!!!
I am using AFNetworking 2.0 to make network calls. I am using the code below for reachability. My problem is that the "Not connected" alert always shows when I open the app. It seems like it takes a while for the app to get connected to the network and that lag is causing the alert to pop up. Is there any way to fix this? I don't want the "Not connected" alert popping up every time and confusing users.
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(#"Reachability: %#", AFStringFromNetworkReachabilityStatus(status));
switch (status) {
{case AFNetworkReachabilityStatusNotReachable:
NSLog(#"No Internet Connection");
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Not connected"
message:#"You have no network connection"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[message show];
}
break;
{case AFNetworkReachabilityStatusReachableViaWiFi:
NSLog(#"WIFI");
}
break;
{case AFNetworkReachabilityStatusReachableViaWWAN:
NSLog(#"4G");
}
break;
default:
NSLog(#"Unkown network status");
break;
}
}];
[[AFNetworkReachabilityManager sharedManager]startMonitoring];
if ([[AFNetworkReachabilityManager sharedManager] isReachable] == NO) {
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Not connected"
message:#"You're not connected to the internet. Please connect via WiFi or data plan"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[message show];
//this shows all the time - why?
}
put this code in your AppDelegate in this method didFinishLaunchingWithOptions. it will display message only one time.
internetReachableFoo = [Reachability reachabilityWithHostname:#"www.google.com"];
internetReachableFoo.reachableBlock = ^(Reachability*reach)
{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"Yayyy, we have the interwebs!");
});
};
internetReachableFoo.unreachableBlock = ^(Reachability*reach)
{
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alrt=[[UIAlertView alloc]initWithTitle:#"Error" message:#"No Internet Connection\nPlease Check The Connection" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alrt show];
});
};
[internetReachableFoo startNotifier];
Because AFNetworkReachabilityManager refreshs its status by notification.
So when you call
[AFNetworkReachabilityManager sharedManager] isReachable]
after the startMonitoring immediately,the status is not get ready.
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
I am using AFNetworking in my App for communicating with server. How can i check whether my host(server) is available or not, i should check this before i am sending a request to server.
Using AFNetworking 2.0 that provide method like below you can check instead of using Reachability class.
- (void)viewDidLoad {
[super viewDidLoad];
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
}
After set start-monitoring in to viewDidLoad you can check any where in to class using Bellow Method.
if ([[AFNetworkReachabilityManager sharedManager] isReachable])
{
NSLog(#"IS REACHABILE");
}
else
{
NSLog(#"NOT REACHABLE");
}
You can try the following code:
Reachability *reach = [Reachability reachabilityWithHostname:#"google.com"];
if ([reach isReachable]) {
// Reachable
if ([reach isReachableViaWiFi]) {
// On WiFi
}
} else {
// Isn't reachable
[reach setReachableBlock:^(Reachability *reachblock)
{
// Now reachable
}];
[reach setUnreachableBlock:^(Reachability*reach)
{
// Now unreachable
}];
}
OR
You can do like this:
AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:#"http://google.com"]];
[client setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
if (status == AFNetworkReachabilityStatusNotReachable) {
// Not reachable
} else {
// Reachable
}
if (status == AFNetworkReachabilityStatusReachableViaWiFi) {
// On wifi
}
}];
NSOperationQueue *operationQueue = self.operationQueue;
// This block is automatically invoked every time the network status changes
[self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case AFNetworkReachabilityStatusNotReachable:
// we need to notify a delegete when internet connection is lost.
// use this delegate to notify the user.
//[delegate internetConnectionLost];
NSLog(#"No Internet Connection");
break;
case AFNetworkReachabilityStatusReachableViaWiFi:
NSLog(#"Host available through WIFI");
break;
case AFNetworkReachabilityStatusReachableViaWWAN:
NSLog(#"Host available through 3G");
break;
default:
NSLog(#"Unkown network status");
[operationQueue setSuspended:YES];
break;
}
}];
[self.reachabilityManager startMonitoring];
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)