Internet checking ios application - iphone

I have created an iPhone application Where i want to check internet connectivity.At the didFinishLaunchingWithOptions method of the app delegate method i wrote
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
viewController1 = [[ViewController1 alloc] initWithNibName:#"ViewController1" title:firstTabTitleGlobal bundle:nil];
viewController2 = [[ViewController2 alloc] initWithNibName:#"ViewController2" title:secondTabTitleGlobal bundle:nil];
newNavController = [[UINavigationController alloc] initWithRootViewController:viewController1];
userNavController = [[UINavigationController alloc] initWithRootViewController:viewController2];
self.tabBarController = [[[UITabBarController alloc] init] autorelease];
self.tabBarController.viewControllers = [NSArray arrayWithObjects:newNavController,userNavController,nil]
Reachability *r = [Reachability reachabilityWithHostName:globalHostName];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
{
[self showAlert:globalNetAlertTitle msg:globalNetAlertMsg];
[activityIndicator stopAnimating];
}
else
{
[activityIndicator stopAnimating];
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
}
}
My Code is ok because when no internet connectivity then show alert.But problem is when no interner then default.png is shown. When i run apps again then the apps runs from the showing default.png. And nothing happen.
Thanks in advance.

application:didFinishLaunchingWithOptions: will only run when an app is launched.
If you want your application to check for availability on subsequent application activation, try putting your code in applicationDidBecomeActive:

What might be better is using NSNotifications, to dynamically tell you if you have connectivity. You can do this with an apple class called 'reachabilty'. Once you have included the file in your project, you can then use something like this;
//in viewDidOnload
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(handleNetworkChange:)
name:kReachabilityChangedNotification object:nil];
reachability = [[Reachability reachabilityForInternetConnection] retain];
[reachability startNotifier];
NetworkStatus status = [reachability currentReachabilityStatus];
if (status == NotReachable) {
//Do something offline
} else {
//Do sometihng on line
}
- (void)handleNetworkChange:(NSNotification *)notice{
NetworkStatus status = [reachability currentReachabilityStatus];
if (status == NotReachable) {
//Show offline image
} else {
//Hide offline image
}
}
(this is the corrected code from Reachability network change event not firing)
You will then be able to update you images as soon as any network change takes place. However don't forget to remove yourself from receiving notifications in the dealloc with;
[[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];
If you need any more information about how to implement this, I would be happy to help!
Jonathan

This works great in Swift 5. Returns a Boolean. It also works on mobile data.
public class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}
var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
/* Only Working for WIFI
let isReachable = flags == .reachable
let needsConnection = flags == .connectionRequired
return isReachable && !needsConnection
*/
// Working for Cellular and WIFI
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
let ret = (isReachable && !needsConnection)
return ret
}
}
hope this helps.

Related

Adding MBProgressHud to MPMoviePlayerController

I am trying to show MBProgressHud to MPMoviePlayerController, for that I am observing notifications for load states of MPMoviePlayer, but somehow Method observing notification never observes notifications for load states other then MPMovieLoadStatePlayable. I show MBProgressHud when video starts streaming but it does not work after it plays and then to pause to download video, Due to this I am unable to engage user while video is loading, If anyone has a better method please mention it or if there is any problem in the following code then let me know.
-(void)movieLoadStateDidChange:(NSNotification*)notification{
MPMoviePlayerController *player = [notification object];
if ((player.loadState & MPMovieLoadStatePlayable) == MPMovieLoadStatePlayable) {
NSLog(#"Load state Playable");
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}else if ((player.loadState & MPMovieLoadStatePlaythroughOK) == MPMovieLoadStatePlaythroughOK){
NSLog(#"Load state Playing");
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}else if ((player.loadState & MPMovieLoadStateStalled) == MPMovieLoadStateStalled){
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
NSLog(#"Load state stalled");
}else if ((player.loadState & MPMovieLoadStateUnknown) == MPMovieLoadStateUnknown){
NSLog(#"Load State unknown");
}
}
Ok .. i got your problem and the problem is that you are not getting notification for load states except MPMovieLoadStatePlayable. so here what you can do is...like below...
write down below notifiations in viewdidload
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(moviePlayerPlaybackDidFinish:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(moviePlayerPlaybackStateDidChange:) name:MPMoviePlayerPlaybackStateDidChangeNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(moviePlayerLoadStateDidChange:) name:MPMoviePlayerLoadStateDidChangeNotification object:nil];
After defining it in ViewDidLoad , implement those functions like below....
- (void) moviePlayerPlaybackDidFinish:(NSNotification *)notification
{
//your code....
MPMovieFinishReason finishReason = [notification.userInfo[MPMoviePlayerPlaybackDidFinishReasonUserInfoKey] integerValue];
NSError *error = notification.userInfo[XCDMoviePlayerPlaybackDidFinishErrorUserInfoKey];
NSString *reason = #"Unknown";
switch (finishReason)
{
case MPMovieFinishReasonPlaybackEnded:
reason = #"Playback Ended";
break;
case MPMovieFinishReasonPlaybackError:
reason = #"Playback Error";
break;
case MPMovieFinishReasonUserExited:
reason = #"User Exited";
break;
}
NSLog(#"Finish Reason: %#%#", reason, error ? [#"\n" stringByAppendingString:[error description]] : #"");
}
- (void) moviePlayerPlaybackStateDidChange:(NSNotification *)notification
{
MPMoviePlayerController *moviePlayerController = notification.object;
NSString *playbackState = #"Unknown";
switch (moviePlayerController.playbackState)
{
case MPMoviePlaybackStateStopped:
playbackState = #"Stopped";
break;
case MPMoviePlaybackStatePlaying:
playbackState = #"Playing";
break;
case MPMoviePlaybackStatePaused:
playbackState = #"Paused";
break;
case MPMoviePlaybackStateInterrupted:
playbackState = #"Interrupted";
break;
case MPMoviePlaybackStateSeekingForward:
playbackState = #"Seeking Forward";
break;
case MPMoviePlaybackStateSeekingBackward:
playbackState = #"Seeking Backward";
break;
}
NSLog(#"Playback State: %#", playbackState);
}
- (void) moviePlayerLoadStateDidChange:(NSNotification *)notification
{
MPMoviePlayerController *moviePlayerController = notification.object;
NSMutableString *loadState = [NSMutableString new];
MPMovieLoadState state = moviePlayerController.loadState;
if (state & MPMovieLoadStatePlayable)
[loadState appendString:#" | Playable"];
if (state & MPMovieLoadStatePlaythroughOK)
[loadState appendString:#" | Playthrough OK"];
if (state & MPMovieLoadStateStalled)
[loadState appendString:#" | Stalled"];
NSLog(#"Load State: %#", loadState.length > 0 ? [loadState substringFromIndex:3] : #"N/A");
}
let me know it is working or not!!!
Happy Coding!!!!

Reachability method (startnotifier) is not calling

Here is my reference code. I have put break point in startnotifier method but it is not being called.
[[NSNotificationCenter defaultCenter] addObserver: self selector: #selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
internetReach = [[Reachability reachabilityForInternetConnection] retain];
[internetReach startNotifier];
I have written this part of code in appdelegate.m (didFinishLaunchingWithOptions).
I have declared var in appdelegate.h like below....
#interface AppDelegate : UIResponder < UIApplicationDelegate >
{
Reachability *internetReach;
Reachability *wifiReach;
Reachability *hostReach;
}
Why breakpoint in startnotifier is not being called and hence nsnotification is not calling observer function if I change the network.
+(BOOL)ConnectedToNetWork
{
Reachability *HostReach = [Reachability reachabilityForInternetConnection];
NetworkStatus internetStatus = [HostReach currentReachabilityStatus];
bool result = false;
if (internetStatus == ReachableViaWiFi)
result = true;
else if(internetStatus==ReachableViaWWAN)
result = true;
return result;
}
use this method whre ever u want to check connection

How To check if wifi option enabled or not

How to check if wifi option is enabled on the iPhone or not (but maybe iPhone not connected to one of the wifi net).
For this you need to import reachability classes in your project.
After then:-
#import "Reachability.h"
In you view DidLoad write:-
- (void)viewDidLoad {
Reachability *internetReach = [[Reachability reachabilityForInternetConnection] retain];
[internetReach startNotifer];
Reachability *wifiReach = [[Reachability reachabilityForLocalWiFi] retain];
[wifiReach startNotifer];
NetworkStatus netStatus1 = [internetReach currentReachabilityStatus];
NetworkStatus netStatus2 = [wifiReach currentReachabilityStatus];
if(netStatus1 == NotReachable && netStatus2 == NotReachable)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Sorry" message:#"This feature requires an internet connection." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
else
{//wifi connection available;
}
}
Found a great line of code for this.
Add the Reachability class to your project and then you can do this:
BOOL isConnectedProperly = ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == ReachableViaWiFi);
First import Reachability files into your project.
-(void)loginButtonTouched
{
bool success = false;
const char *host_name = [#"www.google.com"
cStringUsingEncoding:NSASCIIStringEncoding];
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName
(NULL, host_name);
SCNetworkReachabilityFlags flags;
success = SCNetworkReachabilityGetFlags(reachability, &flags);
bool isAvailable = success && (flags & kSCNetworkFlagsReachable) &&
!(flags & kSCNetworkFlagsConnectionRequired);
if (isAvailable)
{
NSLog(#"Host is reachable: %d", flags);
// Perform Action if Wifi is reachable and Internet Connectivity is present
}
else
{
NSLog(#"Host is unreachable");
// Perform Action if Wifi is reachable and Internet Connectivity is not present
}
}
When loginButtonTouched method is called we check that www.google.com is reachable or not.
SCNetworkReachabilityFlags returns flags which helps us to understand the Status of internet connectivity.
If isAvailable variable returns "true" then Host is
Reachable means Wifi is reachable and Internet Connectivity is present.

Getting problem in checking the internet AND Host Network connection

getting problem is that and how can solve this .I trying the internet is On than my must go for SYNC process .but i was work how can do this.
[TDatasyncmanager chekNetworkStatus:]':
:incompatible types in initialization
:switch quantity not an integer
I am trying to check the internet connection and host network connection like this
TDatasyncmanager.h file
#import "Reachability.h"
#interface TDatasyncmanager : UIViewController
{
Reachability *internetReachable;
Reachability *hostReachable;
BOOL internetActive;
NSMutableData *webData;
}
-(void)chekNetworkStatus:(NSNotification*)notice;
#end
And in TDatasyncmanager.m file
#import "TDatasyncmanager.h"
#import "Reachability.h"
#implementation TDatasyncmanager
#synthesize internetActive;
- (void)viewDidLoad {
[super viewDidLoad];
//check for internet connection
[[NSNotification defaultCenter] addObserver:self selector:#selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];
[internetReachable startNotifier];
//check for apathwa to arandom host exits
hostReachable = [[Reachability reachabilityWithHostName:#"http://www.google.com"]retain];
[hostReachable startNotifier];
if(internetActive == YES)
{
NSLog(#"tokenapi:%# annan %#",tokenapi,Contentid);
NSString *post;
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"%#",postLength);
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://192.168.0.1:88/"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
//[theConnection start];
}
}
}
-(void)chekNetworkStatus:(NSNotification *)notice
{
**//called after network status changes
NetworkStatus *internetStatus = [internetReachable currentReachabilityStatus];//:incompatible types in initialization
switch(internetStatus)//:switch quantity not an integer**
{
case NotReachable:
{
NSLog(#"The internet is down.");
self.internetActive = NO;
break;
}
case ReachableViaWiFi:
{
NSLog(#"The internet is working via WIFI.");
self.internetActive = YES;
break;
}
case ReachableViaWWAN:
{
NSLog(#"The internet is working via WWAN.");
self.internetActive = YES;
break;
}
default:
{
NSLog(#"The internet by defualt is Not working.");
self.internetActive = NO;
break;
}
}
NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
switch (hostStatus)
{
case NotReachable:
{
NSLog(#"The internet is down.");
self.internetActive = NO;
break;
}
case ReachableViaWiFi:
{
NSLog(#"The internet is working Via WIFI.");
self.internetActive = YES;
break;
}
case ReachableViaWWAN:
{
NSLog(#"The internet is working Via WWAN.");
self.internetActive = YES;
break;
}
default:
{
NSLog(#"the internet is down.");
self.internetActive= NO;
}
}
}
for Checking Network Present Status We Need Two Classes
Reachability.h
#import <Foundation/Foundation.h>
#import <SystemConfiguration/SystemConfiguration.h>
typedef enum {
NotReachable = 0,
ReachableViaWiFi,
ReachableViaWWAN
} NetworkStatus;
#define kReachabilityChangedNotification #"kNetworkReachabilityChangedNotification"
#interface Reachability: NSObject
{
BOOL localWiFiRef;
SCNetworkReachabilityRef reachabilityRef;
}
//reachabilityWithHostName- Use to check the reachability of a particular host name.
+ (Reachability*) reachabilityWithHostName: (NSString*) hostName;
//reachabilityWithAddress- Use to check the reachability of a particular IP address.
+ (Reachability*) reachabilityWithAddress: (const struct sockaddr_in*) hostAddress;
//reachabilityForInternetConnection- checks whether the default route is available.
// Should be used by applications that do not connect to a particular host
+ (Reachability*) reachabilityForInternetConnection;
//reachabilityForLocalWiFi- checks whether a local wifi connection is available.
+ (Reachability*) reachabilityForLocalWiFi;
//Start listening for reachability notifications on the current run loop
- (BOOL) startNotifer;
- (void) stopNotifer;
- (NetworkStatus) currentReachabilityStatus;
//WWAN may be available, but not active until a connection has been established.
//WiFi may require a connection for VPN on Demand.
- (BOOL) connectionRequired;
#end
Reachability.m
#import <sys/socket.h>
#import <netinet/in.h>
#import <netinet6/in6.h>
#import <arpa/inet.h>
#import <ifaddrs.h>
#import <netdb.h>
#import <CoreFoundation/CoreFoundation.h>
#import "Reachability.h"
#define kShouldPrintReachabilityFlags 1
static void PrintReachabilityFlags(SCNetworkReachabilityFlags flags, const char* comment)
{
#if kShouldPrintReachabilityFlags
NSLog(#"Reachability Flag Status: %c%c %c%c%c%c%c%c%c %s\n",
(flags & kSCNetworkReachabilityFlagsIsWWAN) ? 'W' : '-',
(flags & kSCNetworkReachabilityFlagsReachable) ? 'R' : '-',
(flags & kSCNetworkReachabilityFlagsTransientConnection) ? 't' : '-',
(flags & kSCNetworkReachabilityFlagsConnectionRequired) ? 'c' : '-',
(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) ? 'C' : '-',
(flags & kSCNetworkReachabilityFlagsInterventionRequired) ? 'i' : '-',
(flags & kSCNetworkReachabilityFlagsConnectionOnDemand) ? 'D' : '-',
(flags & kSCNetworkReachabilityFlagsIsLocalAddress) ? 'l' : '-',
(flags & kSCNetworkReachabilityFlagsIsDirect) ? 'd' : '-',
comment
);
#endif
}
#implementation Reachability
static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info)
{
#pragma unused (target, flags)
NSCAssert(info != NULL, #"info was NULL in ReachabilityCallback");
NSCAssert([(NSObject*) info isKindOfClass: [Reachability class]], #"info was wrong class in ReachabilityCallback");
//We're on the main RunLoop, so an NSAutoreleasePool is not necessary, but is added defensively
// in case someon uses the Reachablity object in a different thread.
NSAutoreleasePool* myPool = [[NSAutoreleasePool alloc] init];
Reachability* noteObject = (Reachability*) info;
// Post a notification to notify the client that the network reachability changed.
[[NSNotificationCenter defaultCenter] postNotificationName: kReachabilityChangedNotification object: noteObject];
[myPool release];
}
- (BOOL) startNotifer
{
BOOL retVal = NO;
SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
if(SCNetworkReachabilitySetCallback(reachabilityRef, ReachabilityCallback, &context))
{
if(SCNetworkReachabilityScheduleWithRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode))
{
retVal = YES;
}
}
return retVal;
}
- (void) stopNotifer
{
if(reachabilityRef!= NULL)
{
SCNetworkReachabilityUnscheduleFromRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
}
}
- (void) dealloc
{
[self stopNotifer];
if(reachabilityRef!= NULL)
{
CFRelease(reachabilityRef);
}
[super dealloc];
}
+ (Reachability*) reachabilityWithHostName: (NSString*) hostName;
{
Reachability* retVal = NULL;
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, [hostName UTF8String]);
if(reachability!= NULL)
{
retVal= [[[self alloc] init] autorelease];
if(retVal!= NULL)
{
retVal->reachabilityRef = reachability;
retVal->localWiFiRef = NO;
}
}
return retVal;
}
+ (Reachability*) reachabilityWithAddress: (const struct sockaddr_in*) hostAddress;
{
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)hostAddress);
Reachability* retVal = NULL;
if(reachability!= NULL)
{
retVal= [[[self alloc] init] autorelease];
if(retVal!= NULL)
{
retVal->reachabilityRef = reachability;
retVal->localWiFiRef = NO;
}
}
return retVal;
}
+ (Reachability*) reachabilityForInternetConnection;
{
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
return [self reachabilityWithAddress: &zeroAddress];
}
+ (Reachability*) reachabilityForLocalWiFi;
{
[super init];
struct sockaddr_in localWifiAddress;
bzero(&localWifiAddress, sizeof(localWifiAddress));
localWifiAddress.sin_len = sizeof(localWifiAddress);
localWifiAddress.sin_family = AF_INET;
// IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0
localWifiAddress.sin_addr.s_addr = htonl(IN_LINKLOCALNETNUM);
Reachability* retVal = [self reachabilityWithAddress: &localWifiAddress];
if(retVal!= NULL)
{
retVal->localWiFiRef = YES;
}
return retVal;
}
#pragma mark Network Flag Handling
- (NetworkStatus) localWiFiStatusForFlags: (SCNetworkReachabilityFlags) flags
{
PrintReachabilityFlags(flags, "localWiFiStatusForFlags");
BOOL retVal = NotReachable;
if((flags & kSCNetworkReachabilityFlagsReachable) && (flags & kSCNetworkReachabilityFlagsIsDirect))
{
retVal = ReachableViaWiFi;
}
return retVal;
}
- (NetworkStatus) networkStatusForFlags: (SCNetworkReachabilityFlags) flags
{
PrintReachabilityFlags(flags, "networkStatusForFlags");
if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
{
// if target host is not reachable
return NotReachable;
}
BOOL retVal = NotReachable;
if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
{
// if target host is reachable and no connection is required
// then we'll assume (for now) that your on Wi-Fi
retVal = ReachableViaWiFi;
}
if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
{
// ... and the connection is on-demand (or on-traffic) if the
// calling application is using the CFSocketStream or higher APIs
if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
{
// ... and no [user] intervention is needed
retVal = ReachableViaWiFi;
}
}
if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
{
// ... but WWAN connections are OK if the calling application
// is using the CFNetwork (CFSocketStream?) APIs.
retVal = ReachableViaWWAN;
}
return retVal;
}
- (BOOL) connectionRequired;
{
NSAssert(reachabilityRef != NULL, #"connectionRequired called with NULL reachabilityRef");
SCNetworkReachabilityFlags flags;
if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags))
{
return (flags & kSCNetworkReachabilityFlagsConnectionRequired);
}
return NO;
}
- (NetworkStatus) currentReachabilityStatus
{
NSAssert(reachabilityRef != NULL, #"currentNetworkStatus called with NULL reachabilityRef");
NetworkStatus retVal = NotReachable;
SCNetworkReachabilityFlags flags;
if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags))
{
if(localWiFiRef)
{
retVal = [self localWiFiStatusForFlags: flags];
}
else
{
retVal = [self networkStatusForFlags: flags];
}
}
return retVal;
}
#end
After That In Which Class You Want To Know STATUS ....
.H
#class Reachability
Reachability* internetReachable;
Reachability* hostReachable;
.m
internetReachable =[Reachability reachabilityForInternetConnection];
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
switch (internetStatus)
{
case Not Reachable:
{
// No Internet Connection
}
default:
{ // Internet Available
}
}
NOTE - it's NSNotificationCenter you want to be referencing - not just NSNotification.

Check if iPhone Internet Tethering is Active [duplicate]

I would like to check to see if I have an Internet connection on iOS using the Cocoa Touch libraries or on macOS using the Cocoa libraries.
I came up with a way to do this using an NSURL. The way I did it seems a bit unreliable (because even Google could one day be down and relying on a third party seems bad), and while I could check to see for a response from some other websites if Google didn't respond, it does seem wasteful and an unnecessary overhead on my application.
- (BOOL)connectedToInternet {
NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://www.google.com"]];
return ( URLString != NULL ) ? YES : NO;
}
Is what I have done bad, (not to mention stringWithContentsOfURL is deprecated in iOS 3.0 and macOS 10.4) and if so, what is a better way to accomplish this?
Important: This check should always be performed asynchronously. The majority of answers below are synchronous so be careful otherwise you'll freeze up your app.
Swift
Install via CocoaPods or Carthage: https://github.com/ashleymills/Reachability.swift
Test reachability via closures
let reachability = Reachability()!
reachability.whenReachable = { reachability in
if reachability.connection == .wifi {
print("Reachable via WiFi")
} else {
print("Reachable via Cellular")
}
}
reachability.whenUnreachable = { _ in
print("Not reachable")
}
do {
try reachability.startNotifier()
} catch {
print("Unable to start notifier")
}
Objective-C
Add SystemConfiguration framework to the project but don't worry about including it anywhere
Add Tony Million's version of Reachability.h and Reachability.m to the project (found here: https://github.com/tonymillion/Reachability)
Update the interface section
#import "Reachability.h"
// Add this to the interface in the .m file of your view controller
#interface MyViewController ()
{
Reachability *internetReachableFoo;
}
#end
Then implement this method in the .m file of your view controller which you can call
// Checks if we have an internet connection or not
- (void)testInternetConnection
{
internetReachableFoo = [Reachability reachabilityWithHostname:#"www.google.com"];
// Internet is reachable
internetReachableFoo.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
internetReachableFoo.unreachableBlock = ^(Reachability*reach)
{
// Update the UI on the main thread
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"Someone broke the internet :(");
});
};
[internetReachableFoo startNotifier];
}
Important Note: The Reachability class is one of the most used classes in projects so you might run into naming conflicts with other projects. If this happens, you'll have to rename one of the pairs of Reachability.h and Reachability.m files to something else to resolve the issue.
Note: The domain you use doesn't matter. It's just testing for a gateway to any domain.
I like to keep things simple. The way I do this is:
//Class.h
#import "Reachability.h"
#import <SystemConfiguration/SystemConfiguration.h>
- (BOOL)connected;
//Class.m
- (BOOL)connected
{
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];
return networkStatus != NotReachable;
}
Then, I use this whenever I want to see if I have a connection:
if (![self connected]) {
// Not connected
} else {
// Connected. Do some Internet stuff
}
This method doesn't wait for changed network statuses in order to do stuff. It just tests the status when you ask it to.
Using Apple's Reachability code, I created a function that'll check this correctly without you having to include any classes.
Include the SystemConfiguration.framework in your project.
Make some imports:
#import <sys/socket.h>
#import <netinet/in.h>
#import <SystemConfiguration/SystemConfiguration.h>
Now just call this function:
/*
Connectivity testing code pulled from Apple's Reachability Example: https://developer.apple.com/library/content/samplecode/Reachability
*/
+(BOOL)hasConnectivity {
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);
if (reachability != NULL) {
//NetworkStatus retVal = NotReachable;
SCNetworkReachabilityFlags flags;
if (SCNetworkReachabilityGetFlags(reachability, &flags)) {
if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
{
// If target host is not reachable
return NO;
}
if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
{
// If target host is reachable and no connection is required
// then we'll assume (for now) that your on Wi-Fi
return YES;
}
if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
{
// ... and the connection is on-demand (or on-traffic) if the
// calling application is using the CFSocketStream or higher APIs.
if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
{
// ... and no [user] intervention is needed
return YES;
}
}
if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
{
// ... but WWAN connections are OK if the calling application
// is using the CFNetwork (CFSocketStream?) APIs.
return YES;
}
}
}
return NO;
}
And it's iOS 5 tested for you.
This used to be the correct answer, but it is now outdated as you should subscribe to notifications for reachability instead. This method checks synchronously:
You can use Apple's Reachability class. It will also allow you to check if Wi-Fi is enabled:
Reachability* reachability = [Reachability sharedReachability];
[reachability setHostName:#"www.example.com"]; // Set your host name here
NetworkStatus remoteHostStatus = [reachability remoteHostStatus];
if (remoteHostStatus == NotReachable) { }
else if (remoteHostStatus == ReachableViaWiFiNetwork) { }
else if (remoteHostStatus == ReachableViaCarrierDataNetwork) { }
The Reachability class is not shipped with the SDK, but rather a part of this Apple sample application. Just download it, and copy Reachability.h/m to your project. Also, you have to add the SystemConfiguration framework to your project.
Here's a very simple answer:
NSURL *scriptUrl = [NSURL URLWithString:#"http://www.google.com/m"];
NSData *data = [NSData dataWithContentsOfURL:scriptUrl];
if (data)
NSLog(#"Device is connected to the Internet");
else
NSLog(#"Device is not connected to the Internet");
The URL should point to an extremely small website. I use Google's mobile website here, but if I had a reliable web server I'd upload a small file with just one character in it for maximum speed.
If checking whether the device is somehow connected to the Internet is everything you want to do, I'd definitely recommend using this simple solution. If you need to know how the user is connected, using Reachability is the way to go.
Careful: This will briefly block your thread while it loads the website. In my case, this wasn't a problem, but you should consider this (credits to Brad for pointing this out).
Here is how I do it in my apps: While a 200 status response code doesn't guarantee anything, it is stable enough for me. This doesn't require as much loading as the NSData answers posted here, as mine just checks the HEAD response.
Swift Code
func checkInternet(flag:Bool, completionHandler:(internet:Bool) -> Void)
{
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
let url = NSURL(string: "http://www.google.com/")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "HEAD"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
request.timeoutInterval = 10.0
NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue.mainQueue(), completionHandler:
{(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
let rsp = response as! NSHTTPURLResponse?
completionHandler(internet:rsp?.statusCode == 200)
})
}
func yourMethod()
{
self.checkInternet(false, completionHandler:
{(internet:Bool) -> Void in
if (internet)
{
// "Internet" aka Google URL reachable
}
else
{
// No "Internet" aka Google URL un-reachable
}
})
}
Objective-C Code
typedef void(^connection)(BOOL);
- (void)checkInternet:(connection)block
{
NSURL *url = [NSURL URLWithString:#"http://www.google.com/"];
NSMutableURLRequest *headRequest = [NSMutableURLRequest requestWithURL:url];
headRequest.HTTPMethod = #"HEAD";
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration ephemeralSessionConfiguration];
defaultConfigObject.timeoutIntervalForResource = 10.0;
defaultConfigObject.requestCachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue: [NSOperationQueue mainQueue]];
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:headRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
if (!error && response)
{
block([(NSHTTPURLResponse *)response statusCode] == 200);
}
}];
[dataTask resume];
}
- (void)yourMethod
{
[self checkInternet:^(BOOL internet)
{
if (internet)
{
// "Internet" aka Google URL reachable
}
else
{
// No "Internet" aka Google URL un-reachable
}
}];
}
Apple supplies sample code to check for different types of network availability. Alternatively there is an example in the iPhone developers cookbook.
Note: Please see #KHG's comment on this answer regarding the use of Apple's reachability code.
You could use Reachability by  (available here).
#import "Reachability.h"
- (BOOL)networkConnection {
return [[Reachability reachabilityWithHostName:#"www.google.com"] currentReachabilityStatus];
}
if ([self networkConnection] == NotReachable) { /* No Network */ } else { /* Network */ } //Use ReachableViaWiFi / ReachableViaWWAN to get the type of connection.
Apple provides a sample app which does exactly this:
Reachability
Only the Reachability class has been updated. You can now use:
Reachability* reachability = [Reachability reachabilityWithHostName:#"www.apple.com"];
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
if (remoteHostStatus == NotReachable) { NSLog(#"not reachable");}
else if (remoteHostStatus == ReachableViaWWAN) { NSLog(#"reachable via wwan");}
else if (remoteHostStatus == ReachableViaWiFi) { NSLog(#"reachable via wifi");}
When using iOS 12 or macOS v10.14 (Mojave) or newer, you can use NWPathMonitor instead of the pre-historic Reachability class. As a bonus you can easily detect the current network connection type:
import Network // Put this on top of your class
let monitor = NWPathMonitor()
monitor.pathUpdateHandler = { path in
if path.status != .satisfied {
// Not connected
}
else if path.usesInterfaceType(.cellular) {
// Cellular 3/4/5g connection
}
else if path.usesInterfaceType(.wifi) {
// Wi-Fi connection
}
else if path.usesInterfaceType(.wiredEthernet) {
// Ethernet connection
}
}
monitor.start(queue: DispatchQueue.global(qos: .background))
More info here: https://developer.apple.com/documentation/network/nwpathmonitor
A version on Reachability for iOS 5 is darkseed/Reachability.h. It's not mine! =)
There's a nice-looking, ARC- and GCD-using modernization of Reachability here:
Reachability
If you're using AFNetworking you can use its own implementation for internet reachability status.
The best way to use AFNetworking is to subclass the AFHTTPClient class and use this class to do your network connections.
One of the advantages of using this approach is that you can use blocks to set the desired behavior when the reachability status changes. Supposing that I've created a singleton subclass of AFHTTPClient (as said on the "Subclassing notes" on AFNetworking docs) named BKHTTPClient, I'd do something like:
BKHTTPClient *httpClient = [BKHTTPClient sharedClient];
[httpClient setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
{
if (status == AFNetworkReachabilityStatusNotReachable)
{
// Not reachable
}
else
{
// Reachable
}
}];
You could also check for Wi-Fi or WLAN connections specifically using the AFNetworkReachabilityStatusReachableViaWWAN and AFNetworkReachabilityStatusReachableViaWiFi enums (more here).
I've used the code in this discussion, and it seems to work fine (read the whole thread!).
I haven't tested it exhaustively with every conceivable kind of connection (like ad hoc Wi-Fi).
Very simple.... Try these steps:
Step 1: Add the SystemConfiguration framework into your project.
Step 2: Import the following code into your header file.
#import <SystemConfiguration/SystemConfiguration.h>
Step 3: Use the following method
Type 1:
- (BOOL) currentNetworkStatus {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
BOOL connected;
BOOL isConnected;
const char *host = "www.apple.com";
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, host);
SCNetworkReachabilityFlags flags;
connected = SCNetworkReachabilityGetFlags(reachability, &flags);
isConnected = NO;
isConnected = connected && (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired);
CFRelease(reachability);
return isConnected;
}
Type 2:
Import header : #import "Reachability.h"
- (BOOL)currentNetworkStatus
{
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];
return networkStatus != NotReachable;
}
Step 4: How to use:
- (void)CheckInternet
{
BOOL network = [self currentNetworkStatus];
if (network)
{
NSLog(#"Network Available");
}
else
{
NSLog(#"No Network Available");
}
}
-(void)newtworkType {
NSArray *subviews = [[[[UIApplication sharedApplication] valueForKey:#"statusBar"] valueForKey:#"foregroundView"]subviews];
NSNumber *dataNetworkItemView = nil;
for (id subview in subviews) {
if([subview isKindOfClass:[NSClassFromString(#"UIStatusBarDataNetworkItemView") class]]) {
dataNetworkItemView = subview;
break;
}
}
switch ([[dataNetworkItemView valueForKey:#"dataNetworkType"]integerValue]) {
case 0:
NSLog(#"No wifi or cellular");
break;
case 1:
NSLog(#"2G");
break;
case 2:
NSLog(#"3G");
break;
case 3:
NSLog(#"4G");
break;
case 4:
NSLog(#"LTE");
break;
case 5:
NSLog(#"Wifi");
break;
default:
break;
}
}
- (void)viewWillAppear:(BOOL)animated
{
NSString *URL = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://www.google.com"]];
return (URL != NULL ) ? YES : NO;
}
Or use the Reachability class.
There are two ways to check Internet availability using the iPhone SDK:
1. Check the Google page is opened or not.
2. Reachability Class
For more information, please refer to Reachability (Apple Developer).
Use http://huytd.github.io/datatify/. It's easier than adding libraries and write code by yourself.
First: Add CFNetwork.framework in framework
Code: ViewController.m
#import "Reachability.h"
- (void)viewWillAppear:(BOOL)animated
{
Reachability *r = [Reachability reachabilityWithHostName:#"www.google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
{
/// Create an alert if connection doesn't work
UIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:#"No Internet Connection" message:NSLocalizedString(#"InternetMessage", nil)delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[myAlert show];
[myAlert release];
}
else
{
NSLog(#"INTERNET IS CONNECT");
}
}
Swift 3 / Swift 4
You must first import
import SystemConfiguration
You can check the Internet connection with the following method:
func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}
var flags = SCNetworkReachabilityFlags()
if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
return false
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
}
First download the reachability class and put reachability.h and reachabilty.m file in your Xcode.
The best way is to make a common Functions class (NSObject) so that you can use it any class. These are two methods for a network connection reachability check:
+(BOOL) reachabiltyCheck
{
NSLog(#"reachabiltyCheck");
BOOL status =YES;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object:nil];
Reachability * reach = [Reachability reachabilityForInternetConnection];
NSLog(#"status : %d",[reach currentReachabilityStatus]);
if([reach currentReachabilityStatus]==0)
{
status = NO;
NSLog(#"network not connected");
}
reach.reachableBlock = ^(Reachability * reachability)
{
dispatch_async(dispatch_get_main_queue(), ^{
});
};
reach.unreachableBlock = ^(Reachability * reachability)
{
dispatch_async(dispatch_get_main_queue(), ^{
});
};
[reach startNotifier];
return status;
}
+(BOOL)reachabilityChanged:(NSNotification*)note
{
BOOL status =YES;
NSLog(#"reachabilityChanged");
Reachability * reach = [note object];
NetworkStatus netStatus = [reach currentReachabilityStatus];
switch (netStatus)
{
case NotReachable:
{
status = NO;
NSLog(#"Not Reachable");
}
break;
default:
{
if (!isSyncingReportPulseFlag)
{
status = YES;
isSyncingReportPulseFlag = TRUE;
[DatabaseHandler checkForFailedReportStatusAndReSync];
}
}
break;
}
return status;
}
+ (BOOL) connectedToNetwork
{
// Create zero addy
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
// Recover reachability flags
SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
SCNetworkReachabilityFlags flags;
BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
CFRelease(defaultRouteReachability);
if (!didRetrieveFlags)
{
NSLog(#"Error. Could not recover network reachability flags");
return NO;
}
BOOL isReachable = flags & kSCNetworkFlagsReachable;
BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
BOOL nonWiFi = flags & kSCNetworkReachabilityFlagsTransientConnection;
NSURL *testURL = [NSURL URLWithString:#"http://www.apple.com/"];
NSURLRequest *testRequest = [NSURLRequest requestWithURL:testURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0];
NSURLConnection *testConnection = [[NSURLConnection alloc] initWithRequest:testRequest delegate:self];
return ((isReachable && !needsConnection) || nonWiFi) ? (testConnection ? YES : NO) : NO;
}
Now you can check network connection in any class by calling this class method.
There is also another method to check Internet connection using the iPhone SDK.
Try to implement the following code for the network connection.
#import <SystemConfiguration/SystemConfiguration.h>
#include <netdb.h>
/**
Checking for network availability. It returns
YES if the network is available.
*/
+ (BOOL) connectedToNetwork
{
// Create zero addy
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
// Recover reachability flags
SCNetworkReachabilityRef defaultRouteReachability =
SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
SCNetworkReachabilityFlags flags;
BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
CFRelease(defaultRouteReachability);
if (!didRetrieveFlags)
{
printf("Error. Could not recover network reachability flags\n");
return NO;
}
BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);
return (isReachable && !needsConnection) ? YES : NO;
}
To do this yourself is extremely simple. The following method will work. Just be sure to not allow a hostname protocol such as HTTP, HTTPS, etc. to be passed in with the name.
-(BOOL)hasInternetConnection:(NSString*)urlAddress
{
SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [urlAddress UTF8String]);
SCNetworkReachabilityFlags flags;
if (!SCNetworkReachabilityGetFlags(ref, &flags))
{
return NO;
}
return flags & kSCNetworkReachabilityFlagsReachable;
}
It is quick simple and painless.
I found it simple and easy to use library SimplePingHelper.
Sample code: chrishulbert/SimplePingHelper (GitHub)
I think this one is the best answer.
"Yes" means connected. "No" means disconnected.
#import "Reachability.h"
- (BOOL)canAccessInternet
{
Reachability *IsReachable = [Reachability reachabilityForInternetConnection];
NetworkStatus internetStats = [IsReachable currentReachabilityStatus];
if (internetStats == NotReachable)
{
return NO;
}
else
{
return YES;
}
}
Download the Reachability file, https://gist.github.com/darkseed/1182373
And add CFNetwork.framework and 'SystemConfiguration.framework' in framework
Do #import "Reachability.h"
First: Add CFNetwork.framework in framework
Code: ViewController.m
- (void)viewWillAppear:(BOOL)animated
{
Reachability *r = [Reachability reachabilityWithHostName:#"www.google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
{
/// Create an alert if connection doesn't work
UIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:#"No Internet Connection" message:NSLocalizedString(#"InternetMessage", nil)delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[myAlert show];
[myAlert release];
}
else
{
NSLog(#"INTERNET IS CONNECT");
}
}
For my iOS projects, I recommend using
Reachability Class
Declared in Swift. For me, it works simply fine with
Wi-Fi and Cellular data
import SystemConfiguration
public class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}
var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
let ret = (isReachable && !needsConnection)
return ret
}
}
Use a conditional statement,
if Reachability.isConnectedToNetwork() {
// Enter your code here
}
}
else {
print("NO Internet connection")
}
This class is useful in almost every case your app uses the Internet connection.
Such as if the condition is true, API can be called or task could be performed.
The Reachability class is OK to find out if the Internet connection is available to a device or not...
But in case of accessing an intranet resource:
Pinging the intranet server with the reachability class always returns true.
So a quick solution in this scenario would be to create a web method called pingme along with other webmethods on the service.
The pingme should return something.
So I wrote the following method on common functions
-(BOOL)PingServiceServer
{
NSURL *url=[NSURL URLWithString:#"http://www.serveraddress/service.asmx/Ping"];
NSMutableURLRequest *urlReq=[NSMutableURLRequest requestWithURL:url];
[urlReq setTimeoutInterval:10];
NSURLResponse *response;
NSError *error = nil;
NSData *receivedData = [NSURLConnection sendSynchronousRequest:urlReq
returningResponse:&response
error:&error];
NSLog(#"receivedData:%#",receivedData);
if (receivedData !=nil)
{
return YES;
}
else
{
NSLog(#"Data is null");
return NO;
}
}
The above method was so useful for me, so whenever I try to send some data to the server I always check the reachability of my intranet resource using this low timeout URLRequest.
Apart from reachability you may also use the Simple Ping helper library. It works really nice and is simple to integrate.