How do you use the iPhone Reachability Notifications [duplicate] - ios

This question already has answers here:
How can I check for an active Internet connection on iOS or macOS?
(46 answers)
Closed 9 years ago.
I have the following code:
- (void) testInternetConnection {
internetConnection = [Reachability reachabilityWithHostname:#"www.google.com"];
// Internet is reachable
internetConnection.reachableBlock = ^(Reachability*reach)
{
// Update the UI on the main thread
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"Yayyy, we have the interwebs!");
});
};
// Internet is not reachable
internetConnection.unreachableBlock = ^(Reachability*reach)
{
// Update the UI on the main thread
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"Someone broke the internet :(");
});
};
[internetConnection startNotifier];
}
How do I tell if my internet has changed using the notifier? I understand the singleton method and use that when needed.

try to test your code on device when ever possible.
ensure
BOOL status = ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable)
, on device if you are testing in simulator
The simulator just uses your default Mac network connection so you need to disconnect your mac from the network and the simulator will experience the same loss of network connectivity.
Thanks

you can check reachability by this code,
//to make reachability object
reachability = [Reachability reachabilityForInternetConnection];
//start notifier
[reachability startNotifier];
//get reachability status
remoteHostStatus = [reachability currentReachabilityStatus];
Thanks.

//First import Reachability classes
// In Appdelegate .h file create variables
Reachability *hostReach,*internetReach,*wifiReach;
Reachability *internetReachable;
// After that add this code didfinish lonching with options
internetReachable = [Reachability reachabilityForInternetConnection] ;
[internetReachable startNotifier];
-(BOOL) connectedToNetwork
{
const char *host_name = "www.google.com";
BOOL _isDataSourceAvailable = NO;
Boolean success;
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL,host_name);
SCNetworkReachabilityFlags flags;
success = SCNetworkReachabilityGetFlags(reachability, &flags);
_isDataSourceAvailable = success &&
(flags & kSCNetworkFlagsReachable) &&
!(flags & kSCNetworkFlagsConnectionRequired);
CFRelease(reachability);
return _isDataSourceAvailable;
}

Related

How to check if WIFI button is enabled (iOS)

I want to be able to check to see if the user is connected to WiFi, but not connected to a network. So basically I want to check the state of the WiFi button on the device setting page to check if button is enabled or disabled.
At the moment I can check to see if the Wifi is connected to a network or not connected to an network doing the following:
BOOL hasWiFiNetwork = NO;
NSArray *interfaces = CFBridgingRelease(CNCopySupportedInterfaces());
for (NSString *interface in interfaces)
{
NSDictionary *networkInfo = CFBridgingRelease(CNCopyCurrentNetworkInfo((__bridge CFStringRef)(interface)));
if (networkInfo != NULL)
{
hasWiFiNetwork = YES;
break;
}
else
{
hasWiFiNetwork = NO;
break;
}
}
Try this code and use Reachability class.
BOOL isConnectedProperly = ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == ReachableViaWiFi);
Update
It turns out that it isn't possible, there is no API/Framework/BOOL value that can do this because Apple havn't added any kind of ability to check to see if the WiFi is switched on or off for developers. As explained nicely here: https://stackoverflow.com/a/12906461/4657588
Then this SO post should be what you want: https://stackoverflow.com/a/7938778/4657588
Reachability *reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];
NetworkStatus status = [reachability currentReachabilityStatus];
if (status == ReachableViaWiFi) {
// WiFi
}
else {
// Either WiFi is off or we are not connected to a WiFi network.
}
First you need to download reachability file from apple developer site
and after that add these piece of code every time where ever yu want to check.
-(BOOL)isConnectedTointernet{
BOOL status = NO;
Reachability *reachability = [Reachability reachabilityForInternetConnection];
int networkStatus = reachability.currentReachabilityStatus;
status = (networkStatus != NotReachable)? YES:NO;
return status;}

iOS - Connection checker with Reachability class is failed. (reachabilityWithHostName:)

I wrote a connection checker using Apple's Reachability class' reachabilityWithHostName: method. Here is my code.
-(BOOL)checkConnection{
Reachability *reachability = [Reachability reachabilityWithHostName:#"www.example.com"];
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
if (remoteHostStatus != NotReachable) {
return YES;
}
else {return NO;}
}
SO here is the use cases:
if I have wifi connection** : returns YES as expected.
If I have cellular connection : returns YES as expected.
If cellular and Wifi is disabled : returns NO as expected.
If I have WiFi connection; but the DSL cable is unplugged (so the host shouldn't
be reachable, internet connection is not available.) : returns YES and it's unexpected.
Also if cellular is enabled but at my current position I have no signal : returns YES and it's unexpected.
How can I solve these unexpected results?
Thank you.
With #Martin Koles' help I added a html file into the server. It only has a random value inside. Now I check reachability. If server is reachable, I am trying to get the value from html file. Than, if I could get the value returning YES. If I couldn't (the serverValue should be nil) returning NO..
-(BOOL)checkConnection{
Reachability *reachability = [Reachability reachabilityWithHostName:#"www.izmirmobil.com"];
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
if (remoteHostStatus != NotReachable) {
NSURL *url = [NSURL URLWithString:#"http://www.example.com/getAValue.html"];
NSError *errr = nil;
NSStringEncoding enc;
NSString *serverValue = [[NSString alloc] initWithContentsOfURL:url usedEncoding:&enc error:&errr];
if(serverValue)return YES;
else return NO;
}
else {return NO;}
}

How can i find programmatically iPhone device connected 3G network or Wifi in iOS7

Hi i need to find out whether iPhone internet connected 3G or 2G or WIFI network
any suggestions
Thanks
Sravan
Download Reachability Class for iOS from this link:- https://github.com/tonymillion/Reachability
1)Add Reachability.h &.m in your Project, make sure you make it ARC compatible by adding flag -fno-objc-arc
2)Now, check the connection type in your view controller
Reachability *reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];
NetworkStatus status = [reachability currentReachabilityStatus];
if(status == NotReachable)
{
//No internet
}
else if (status == ReachableViaWiFi)
{
//WiFi
}
else if (status == ReachableViaWWAN)
{
//3G
}
You can use the Reachability library written by tonymillion.
If you don't wan to use ARC, there is also the Apple Reachability library.
Also take a look inside of < CoreTelephony/CTTelephonyNetworkInfo.h >
You will see that there is a currentRadioAccessTechnology property exposed on CTTelephonyNetworkInfo.
CTTelephonyNetworkInfo *netInfo = [[CTTelephonyNetworkInfo alloc] init];
NSLog(#"Radio access technology:\n%#",
netInfo.currentRadioAccessTechnology);
You can subscribe to changes via:
[NSNotificationCenter.defaultCenter
addObserverForName:CTRadioAccessTechnologyDidChangeNotification
object:nil
queue:nil
usingBlock:^(NSNotification __unused *notification) {
CTTelephonyNetworkInfo *current =
[[CTTelephonyNetworkInfo alloc] init];
NSLog(#"Updated Radio access technology:\n%#",
current.currentRadioAccessTechnology);
}];

Testing the internet connection is not working with Reachability

I am using the updated Reachability library to test whether the internet connexion is reachable. I try to Log a message in case the internet is not reachable, but the Log doesn't debug:
//Test the internet connection
Reachability* reach = [Reachability reachabilityForInternetConnection];
reach.unreachableBlock = ^(Reachability*reach)
{
NSLog(#"Internet connexion unreachable");//Although Internet cnx is off, this message is not displayed
return;
};
// start the notifier which will cause the reachability object to retain itself!
[reach startNotifier];
Am I misunderstanding the Reachability library? How to perform a given task when Internet is off? Thanx.
P.S: My iPad is only wifi, without 3G service.
Using Alamofire to check interner, In Swift 4
import Foundation
import Alamofire
class Connectivity {
class func isConnectedToInternet() ->Bool {
return NetworkReachabilityManager()!.isReachable
}
}
Then call this function
if Connectivity.isConnectedToInternet() {
print("Yes! internet is available.")
// do some tasks..
}
Actually, you should register for a notification to receive changed reachibility :
[[NSNotificationCenter defaultCenter] addObserver: self selector: #selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
Look at Apple example here : http://developer.apple.com/library/ios/#samplecode/Reachability/Listings/Classes_ReachabilityAppDelegate_m.html#//apple_ref/doc/uid/DTS40007324-Classes_ReachabilityAppDelegate_m-DontLinkElementID_4
Ok, so best way I got is following Apple sample code:
//Test the internet connection
Reachability* reach = [Reachability reachabilityForInternetConnection];
NetworkStatus netStatus = [reach currentReachabilityStatus];
//See if the reachable object status is "ReachableViaWifi"
if (netStatus!=ReachableViaWiFi) {
//If not
NSLog(#"wifi unavailable");
//Alert the user about the Internet cnx
WBErrorNoticeView *notice = [WBErrorNoticeView errorNoticeInView:self.view title:#"Network Error" message:#"Check your internet connection."];
notice.sticky = NO;
[notice show];
return;//Exit the method
}

iOS Reachability: Problem with host Method

I have create a method to check if the host is reachable. I had download the Reachability class (both .h & .m) from apple developer websites and import to my project. I have pass the NSString Name as the URL (host Name). The hostName is http://www.google.com. However, no matter what host name I pass to this method and its always return NO (connectToHost). The code as below:
- (BOOL) checkHostAvailability:(NSString *)Name{
BOOL connectToHost;
hostReach = [[Reachability reachabilityWithHostName:Name] retain];
[hostReach startNotifier];
NetworkStatus hostStatus = [hostReach currentReachabilityStatus];
NSLog(#"Name: %#", Name);
NSLog(#"hostStatus is %#", hostStatus);
if(hostStatus == NotReachable){
NSLog(#"Here is the checkHostAvailability Method and host NOT reachable");
connectToHost = NO;
}else{
NSLog(#"Here is the checkHostAvailability Method and host is reachable");
connectToHost = YES;
}
return connectToHost;
}
After a few hours of investigation, I have found out that the NetworkStatus hostStatus always equal to null. I assume this is why this method is not working. And I have spend 8 hours to find out the problem with this code and search out this website, however I still couldn't find the problem and solution.
Please help and much appreciated.
Remove the 'http://' from the host name.
If you wanted to use http://www.google.com as your host, you would pass 'google.com' as the hostname. Do not include http://, the ending slash or anything that could follow an ending slash. www. is fine to include.
[Reachability reachabilityWithHostName:#"google.com"];
This is the code I use for all the connection checks (see here: iOS Developer Library -Reachability) and it is working fine for me :
-(BOOL) hasConnection{
//check network status _ iphone settings
Reachability *internetReachability = [Reachability reachabilityForInternetConnection];
[internetReachability startNotifier];
NetworkStatus status=[internetReachability currentReachabilityStatus];
if (status == NotReachable) {
NSLog(#"No internet");
//[internetReachability stopNotifier];
return NO;
}else {
NSLog(#"Internet is ON");
// [internetReachability stopNotifier];
//check internet connection _reachable path
Reachability *hostReachable=[Reachability reachabilityWithHostName:#"www.apple.com"];
BOOL connectionRequired =[hostReachable connectionRequired];
NSLog(#"%hhd",connectionRequired);
[hostReachable startNotifier];
Reachability *wifiReachability=[Reachability reachabilityForLocalWiFi];
[wifiReachability startNotifier];
NetworkStatus hostStatus=[hostReachable currentReachabilityStatus];
if(hostStatus == NotReachable){
NSLog(#"No internet connection");
[hostReachable stopNotifier];
return NO;
}else{
NSLog(#"Connection is ok");
[hostReachable stopNotifier];
return YES;
}
}
}

Resources