The method below works very well for checking to see if a user has an internet connection. I would like to check for an internet connection throughout my entire app, and am wondering if there is somewhere I can put it within my App Delegate where it will get called from every view controller.
Is there a way to do this? Doesn't seem to work properly if I put it in my applicationDidFinishLaunching. Any recommendations would be great! Thank you!
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");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Internet Connectivity"
message:#"You must have an internet connection" delegate:self cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alert show];
return;
}
If you're looking to place this particular method in a location that can be accessed and called from the entirety of your application then this is simply a design decision. There are a number of ways to achieve this.
I like to make use of the singleton paradigm when implementing global methods. John Wordsworth covers this in a nice succinct blog post here:
http://www.johnwordsworth.com/2010/04/iphone-code-snippet-the-singleton-pattern/
Here's a quick chunk of code:
InternetConnectionChecker.h
#import <Foundation/Foundation.h>
#interface InternetConnectionChecker : NSObject
// Accessor for singelton instance of internet connection checker.
+ (InternetConnectionChecker *)sharedInternetConnectionChecker;
// Check to see whether we have a connection to the internet. Returns YES or NO.
- (BOOL)connected;
#end
InternetConnectionChecker.m
#import "InternetConnectionChecker.h"
#implementation InternetConnectionChecker
// Accessor for singelton instance of internet connection checker.
+ (InternetConnectionChecker *)sharedInternetConnectionChecker
{
static InternetConnectionChecker *sharedInternetConnectionChecker;
#synchronized(self)
{
if (!sharedInternetConnectionChecker) {
sharedInternetConnectionChecker = [[InternetConnectionChecker alloc] init];
}
}
return sharedInternetConnectionChecker;
}
// Check to see whether we have a connection to the internet. Returns YES or NO.
- (BOOL)connected
{
NSURL *scriptUrl = [NSURL URLWithString:#"http://www.google.com/m"];
NSData *data = [NSData dataWithContentsOfURL:scriptUrl];
if (data) {
NSLog(#"Device is connected to the internet");
return TRUE;
}
else {
NSLog(#"Device is not connected to the internet");
return FALSE;
}
}
#end
In my example I've amended your method to return a true/false so you can handle the result within the UI calling the method appropriately but you could continue to show a UIAlertView if you pleased.
You would then use the singleton in the following way:
InternetConnectionChecker *checker = [InternetConnectionChecker sharedInternetConnectionChecker];
BOOL connected = [checker connected];
There are of course more complex ways of doing it, but the easiest way, (and the way I use) is to simply create a "CheckNetwork" class with your method as a class method which returns a bool, i.e:
+ (BOOL) checkConnection{
yourMethodDetails;
}
then simply #import "CheckNetwork.h" into any file in your project and call
if([CheckNetwork checkConnection]){
whatever you want to do here;
}
While Singleton class and Static methods are a way, you could also implement static inline methods in a .h file which as no .m file
Also, as a sidetalk, checking internet connectivity using using NSURL along with google.com is not a good practice.
Because,
It is not a simple ping operation
It downloads the whole page which may consume time
OS provided ways are more radical and appropriate.
It you are working with a specific web site, then using that web site for connectivity is the best practice, i think. See this Answer by Jon Skeet
I would suggest using the Reachability framework by Apple.
Or if you need more compact single function version, you could also use this function excerpted from Reachabilty myself
+ (BOOL) reachabilityForInternetConnection;
{
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);
SCNetworkReachabilityFlags flags;
if (SCNetworkReachabilityGetFlags(reachability, &flags))
{
return (flags & kSCNetworkReachabilityFlagsConnectionRequired);
}
return NO;
}
To make use of global variables and methods I implemented Singleton as a healthy coding practice. I followed Apple documents, john wordsworth blog before implementing it. In the first, I did not make my singleton thread safe and I implemented this method along with all other mentioned in the blog and Apple document.
+ (SingletonClass *)sharedManager
{
static SingletonClass *sharedManager = nil;
if (sharedManager == nil) {
sharedManager = [[super allocWithZone:NULL] init];
}
return sharedManager;
}
After that to make Singleton thread safe I made changes to + (SingletonClass *)sharedManager class like this and my app stops launching. I put break points and observed dispatch_once gets called twice and then code stops executing further.
+(SingletonClass *)sharedManager
{
static SingletonClass *sharedManager = nil;
if (sharedManager !=nil)
{
return sharedManager;
}
static dispatch_once_t pred;
dispatch_once(&pred, ^{
sharedManager = [SingletonClass alloc];
sharedManager=[sharedManager init];
});
return sharedManager;
}
If i remove this thread safe code snippet and revert back to previous code it works fine and code gets executed.
Please note that I also looked at the bbum's answer here in which he has mentioned possible deadlock situation before asking question but I am not able to figure out the issue. Any explanation or solution will be helpful for me. Thanks.
Edit 1:
In case someone wants to look at the complete code, I have created gist for that. Please follow there. Thanks.
Let's consider what happens if two threads call second version of sharedManager almost simultaneously.
Thread 1 calls first. It checks sharedManager !=nil, which is false, so it goes on to the dispatch_once. In the dispatch_once block, it executes [SingletonClass alloc] and stores the result in sharedManager.
Now, before thread 1 continues on to the next line, thread 2 comes along and calls sharedManager. Thread 2 checks sharedManager !=nil, which is now true. So it returns sharedManager, and the caller then tries to use sharedManager. But at this time, sharedManager hasn't been fully initialized yet. That's bad.
You cannot set sharedManager until you have a fully initialized object to set it to. Also (as borrrden pointed out), you don't need the sharedManager !=nil check at the top, because dispatch_once is very efficient anyway.
+ (SingletonClass *)sharedManager {
static dispatch_once_t pred;
static SingletonClass *sharedManager;
dispatch_once(&pred, ^{
sharedManager = [[SingletonClass alloc] init];
});
return sharedManager;
}
Now, I've looked at your gist and your problem is here:
+ (id)allocWithZone:(NSZone*)zone {
return [[self sharedManager] retain];
}
Your +[SingletonClass sharedManager] method calls +[SingletonClass alloc] in the dispatch_once block. Since you don't override alloc, +[SingletonClass alloc] calls +[SingletonClass allocWithZone:NULL]. And +[SingletonClass allocWithZone:] method calls +[SingletonClass sharedManager]. On this second call to sharedManager, your program hangs in dispatch_once, because you're still inside the first call to dispatch_once.
The simplest fix is to remove your implementation of allocWithZone:. Just document that sharedManager is the only supported way to get an instance of SingletonClass and move on.
If you want to be obtuse and make [[SingletonClass alloc] init] return the singleton, even if you do it repeatedly, it's complicated. Don't try to override alloc or allocWithZone:. Do this:
static SingletonClass *sharedManager; // outside of any method
+ (SingletonClass *)sharedManager {
return sharedManager ? sharedManager : [[SingletonClass alloc] init];
}
- (id)init {
static dispatch_once_t once;
dispatch_once(&once, ^{
if (self = [super init]) {
// initialization here...
sharedManager = self;
}
});
self = sharedManager;
return self;
}
You don't need the check on the top, get rid of the if statement. The dispatch_once guarantees that the block will only be executed once in the lifetime of the application so the first check is redundant.
More Info:
http://cocoasamurai.blogspot.jp/2011/04/singletons-your-doing-them-wrong.html
I'm writing an iPhone app that involves handling network events from a server over a VoIP socket in the background. I've successfully set up the socket, the background service info in the .plist, and the appropriate streams, but I'm having trouble figuring out how to do anything useful in my callback. I don't know how to access the rest of my application's state from within the callback function. Here is where I set up the connections in the AppDelegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
NSLog(#"AppDelegate: didFinishLaunchingWithOptions");
// Override point for customization after application launch.
// Add the view controller's view to the window and display.
[self.window addSubview:viewController.view];
[self.window makeKeyAndVisible];
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFHostRef host = CFHostCreateWithName(kCFAllocatorDefault, (CFStringRef)#"irc.freenode.net");
CFStreamCreatePairWithSocketToCFHost(kCFAllocatorDefault, host, 6667, &readStream, &writeStream);
CFReadStreamSetProperty(readStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
CFWriteStreamSetProperty(writeStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
CFStreamClientContext myContext = {
0,
viewController,
(void *(*)(void *info))CFRetain,
(void (*)(void *info))CFRelease,
(CFStringRef (*)(void *info))CFCopyDescription
};
CFOptionFlags registeredEvents = kCFStreamEventHasBytesAvailable |
kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered;
if(CFReadStreamSetClient(readStream, registeredEvents, clientCB, &myContext)) {
CFReadStreamScheduleWithRunLoop(readStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
}
if (!CFReadStreamOpen(readStream)) {
NSLog(#"Read stream could not be opened");
}
else {
NSLog(#"Successfully opened read stream");
}
return YES;
}
And here is the callback function for CFStream events, where I'm having my issues:
void clientCB(CFReadStreamRef stream, CFStreamEventType event, void* myPtr) {
switch(event) {
case kCFStreamEventHasBytesAvailable:{
UInt8 buf[32];
CFIndex bytesRead = CFReadStreamRead(stream, buf, 32);
if (bytesRead > 0) {
NSLog(#"Readstream Not Empty %i", buf[0]);//dummy debug marker
}
//I WANT TO ACCESS CLASSES, PROPERTIES, FUNCTIONS, ETC. ABOUT THE REST OF MY PROGRAM HERE (E.G. GET A WORKING POINTER BACK TO THE MAIN APPDELEGATE).
break;
}
case kCFStreamEventErrorOccurred:
case kCFStreamEventEndEncountered:
default:
break;
}
}
These two functions are both defined in the same AppDelegate class. I've tried passing pointers via the CFStreamClientContext struct: VoIP_TestViewController* testViewController = context->info;, I've tried to access the main appDelegate via: [[UIApplication sharedApplication] delegate], and I've tried the usual Obj-C and C constructs ("this", "self", "super").
Any help would be greatly greatly appreciated!
Make sure you import your main app delegate header file into the view where you need to call it.
Use this to call it:
nameOfYourAppDelegate *appDelegate = (_nameOfYourAppDelegate *)[[UIApplication sharedApplication] delegate];
//than you can use appDelegate for whatever you want (ie. appDelegate.somView.someProperty )
Ah I'm an idiot. I forgot to import a class header for a member class (i.e. I forgot to import ClassB when I tried to access [ClassA.ClassB methodB]). Of course XCode only provided an unrecognized selector runtime error rather than a missing declaration compiler error, making debugging slightly harder than it should have been. Thanks for the catch!
Long time lurker, first time poster.
I'm making a ServerConnection module to make it a whole lot modular and easier but am having trouble getting the delegate called. I've seen a few more questions like this but none of the answers fixed my problem.
ServerConnection is set up as a protocol. So a ServerConnection object is created in Login.m which makes the call to the server and then add delegate methods in Login to handle if there's an error or if it's done, these are called by ServerConnection like below.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if( [self.delegate respondsToSelector:#selector(connectionDidFinish:)]) {
NSLog(#"DOES RESPOND");
[self.delegate connectionDidFinish:self];
} else {
NSLog(#"DOES NOT RESPOND");
}
self.connection = nil;
self.receivedData = nil;
}
It always "does not respond". I've tried the CFRunLoop trick (below) but it still doesn't work.
- (IBAction)processLogin:(id)sender {
// Hide the keyboard
[sender resignFirstResponder];
// Start new thread
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// Acutally call the server
[self authenticate];
// Prevent the thread from exploding before we've got the data
CFRunLoopRun();
// End thread
[pool release];
}
I copied the Apple URLCache demo pretty heavily and have compared them both many times but can't find any discrepancies.
Any help would be greatly appreciated.
Here are the questions to ask:
Does your delegate respond to connectionDidFinishLoading:?
Does the signature match, i.e. it takes another object?
Is the delegate set at all or is it nil? (Check this in that very method)
If any of those are "NO", you will see "doesn't respond"... and all equally likely to happen in your application, but all are easy to figure out.
I'm working on an iPhone app and I'd like to be able to check if the phone is able to make phone calls (and warn the user if not). This could be due to no cellular service being available or if the user has placed the phone in "airplane mode".
I've looked around Apple's docs and I can't find anything that would let me check this. Am I missing something, or does Apple not expose this information to apps?
EDIT: Just to emphasize, I'm not interested in checking for an IP network connection, but would like to determine if my app can make a phone call.
Look at reachability.m. Although I'm not positive about cell signal strength, if something similar exists, it would be contained in this file.
Here's an example of how to use it to detect network reachability: http://www.raddonline.com/blogs/geek-journal/iphone-sdk-testing-network-reachability/
Reachability.m:
/*
===== IMPORTANT =====
This is sample code demonstrating API, technology or techniques in development.
Although this sample code has been reviewed for technical accuracy, it is not
final. Apple is supplying this information to help you plan for the adoption of
the technologies and programming interfaces described herein. This information
is subject to change, and software implemented based on this sample code should
be tested with final operating system software and final documentation. Newer
versions of this sample code may be provided with future seeds of the API or
technology. For information about updates to this and other developer
documentation, view the New & Updated sidebars in subsequent documentation
seeds.
=====================
File: Reachability.m
Abstract: SystemConfiguration framework wrapper.
Version: 1.4
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc.
("Apple") in consideration of your agreement to the following terms, and your
use, installation, modification or redistribution of this Apple software
constitutes acceptance of these terms. If you do not agree with these terms,
please do not use, install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject
to these terms, Apple grants you a personal, non-exclusive license, under
Apple's copyrights in this original Apple software (the "Apple Software"), to
use, reproduce, modify and redistribute the Apple Software, with or without
modifications, in source and/or binary forms; provided that if you redistribute
the Apple Software in its entirety and without modifications, you must retain
this notice and the following text and disclaimers in all such redistributions
of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may be used
to endorse or promote products derived from the Apple Software without specific
prior written permission from Apple. Except as expressly stated in this notice,
no other rights or licenses, express or implied, are granted by Apple herein,
including but not limited to any patent rights that may be infringed by your
derivative works or by other works in which the Apple Software may be
incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2008 Apple Inc. All Rights Reserved.
*/
#import <sys/socket.h>
#import <netinet/in.h>
#import <netinet6/in6.h>
#import <arpa/inet.h>
#import <ifaddrs.h>
#include <netdb.h>
#import "Reachability.h"
#import <SystemConfiguration/SCNetworkReachability.h>
static NSString *kLinkLocalAddressKey = #"169.254.0.0";
static NSString *kDefaultRouteKey = #"0.0.0.0";
static Reachability *_sharedReachability;
// A class extension that declares internal methods for this class.
#interface Reachability()
- (BOOL)isAdHocWiFiNetworkAvailableFlags:(SCNetworkReachabilityFlags *)outFlags;
- (BOOL)isNetworkAvailableFlags:(SCNetworkReachabilityFlags *)outFlags;
- (BOOL)isReachableWithoutRequiringConnection:(SCNetworkReachabilityFlags)flags;
- (SCNetworkReachabilityRef)reachabilityRefForHostName:(NSString *)hostName;
- (SCNetworkReachabilityRef)reachabilityRefForAddress:(NSString *)address;
- (BOOL)addressFromString:(NSString *)IPAddress address:(struct sockaddr_in *)outAddress;
- (void)stopListeningForReachabilityChanges;
#end
#implementation Reachability
#synthesize networkStatusNotificationsEnabled = _networkStatusNotificationsEnabled;
#synthesize hostName = _hostName;
#synthesize address = _address;
#synthesize reachabilityQueries = _reachabilityQueries;
+ (Reachability *)sharedReachability
{
if (!_sharedReachability) {
_sharedReachability = [[Reachability alloc] init];
// Clients of Reachability will typically call [[Reachability sharedReachability] setHostName:]
// before calling one of the status methods.
_sharedReachability.hostName = nil;
_sharedReachability.address = nil;
_sharedReachability.networkStatusNotificationsEnabled = NO;
_sharedReachability.reachabilityQueries = [[NSMutableDictionary alloc] init];
}
return _sharedReachability;
}
- (void) dealloc
{
[self stopListeningForReachabilityChanges];
[_sharedReachability.reachabilityQueries release];
[_sharedReachability release];
[super dealloc];
}
- (BOOL)isReachableWithoutRequiringConnection:(SCNetworkReachabilityFlags)flags
{
// kSCNetworkReachabilityFlagsReachable indicates that the specified nodename or address can
// be reached using the current network configuration.
BOOL isReachable = flags & kSCNetworkReachabilityFlagsReachable;
// This flag indicates that the specified nodename or address can
// be reached using the current network configuration, but a
// connection must first be established.
//
// As an example, this status would be returned for a dialup
// connection that was not currently active, but could handle
// network traffic for the target system.
//
// If the flag is false, we don't have a connection. But because CFNetwork
// automatically attempts to bring up a WWAN connection, if the WWAN reachability
// flag is present, a connection is not required.
BOOL noConnectionRequired = !(flags & kSCNetworkReachabilityFlagsConnectionRequired);
if ((flags & kSCNetworkReachabilityFlagsIsWWAN)) {
noConnectionRequired = YES;
}
return (isReachable && noConnectionRequired) ? YES : NO;
}
// Returns whether or not the current host name is reachable with the current network configuration.
- (BOOL)isHostReachable:(NSString *)host
{
if (!host || ![host length]) {
return NO;
}
SCNetworkReachabilityFlags flags;
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, [host UTF8String]);
BOOL gotFlags = SCNetworkReachabilityGetFlags(reachability, &flags);
CFRelease(reachability);
if (!gotFlags) {
return NO;
}
return [self isReachableWithoutRequiringConnection:flags];
}
// This returns YES if the address 169.254.0.0 is reachable without requiring a connection.
- (BOOL)isAdHocWiFiNetworkAvailableFlags:(SCNetworkReachabilityFlags *)outFlags
{
// Look in the cache of reachability queries for one that matches this query.
ReachabilityQuery *query = [self.reachabilityQueries objectForKey:kLinkLocalAddressKey];
SCNetworkReachabilityRef adHocWiFiNetworkReachability = query.reachabilityRef;
// If a cached reachability query was not found, create one.
if (!adHocWiFiNetworkReachability) {
// Build a sockaddr_in that we can pass to the address reachability query.
struct sockaddr_in sin;
bzero(&sin, sizeof(sin));
sin.sin_len = sizeof(sin);
sin.sin_family = AF_INET;
// IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0
sin.sin_addr.s_addr = htonl(IN_LINKLOCALNETNUM);
adHocWiFiNetworkReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&sin);
query = [[[ReachabilityQuery alloc] init] autorelease];
query.hostNameOrAddress = kLinkLocalAddressKey;
query.reachabilityRef = adHocWiFiNetworkReachability;
// Add the reachability query to the cache.
[self.reachabilityQueries setObject:query forKey:kLinkLocalAddressKey];
}
// If necessary, register for notifcations for the SCNetworkReachabilityRef on the current run loop.
// If an existing SCNetworkReachabilityRef was found in the cache, we can reuse it and register
// to receive notifications from it in the current run loop, which may be different than the run loop
// that was previously used when registering the SCNetworkReachabilityRef for notifications.
// -scheduleOnRunLoop: will schedule only if network status notifications are enabled in the Reachability instance.
// By default, they are not enabled.
[query scheduleOnRunLoop:[NSRunLoop currentRunLoop]];
SCNetworkReachabilityFlags addressReachabilityFlags;
BOOL gotFlags = SCNetworkReachabilityGetFlags(adHocWiFiNetworkReachability, &addressReachabilityFlags);
if (!gotFlags) {
// There was an error getting the reachability flags.
return NO;
}
// Callers of this method might want to use the reachability flags, so if an 'out' parameter
// was passed in, assign the reachability flags to it.
if (outFlags) {
*outFlags = addressReachabilityFlags;
}
return [self isReachableWithoutRequiringConnection:addressReachabilityFlags];
}
// ReachabilityCallback is registered as the callback for network state changes in startListeningForReachabilityChanges.
static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void *info)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// Post a notification to notify the client that the network reachability changed.
[[NSNotificationCenter defaultCenter] postNotificationName:#"kNetworkReachabilityChangedNotification" object:nil];
[pool release];
}
// Perform a reachability query for the address 0.0.0.0. If that address is reachable without
// requiring a connection, a network interface is available. We'll have to do more work to
// determine which network interface is available.
- (BOOL)isNetworkAvailableFlags:(SCNetworkReachabilityFlags *)outFlags
{
ReachabilityQuery *query = [self.reachabilityQueries objectForKey:kDefaultRouteKey];
SCNetworkReachabilityRef defaultRouteReachability = query.reachabilityRef;
if (!defaultRouteReachability) {
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
ReachabilityQuery *query = [[[ReachabilityQuery alloc] init] autorelease];
query.hostNameOrAddress = kDefaultRouteKey;
query.reachabilityRef = defaultRouteReachability;
[self.reachabilityQueries setObject:query forKey:kDefaultRouteKey];
}
// If necessary, register for notifcations for the SCNetworkReachabilityRef on the current run loop.
// If an existing SCNetworkReachabilityRef was found in the cache, we can reuse it and register
// to receive notifications from it in the current run loop, which may be different than the run loop
// that was previously used when registering the SCNetworkReachabilityRef for notifications.
// -scheduleOnRunLoop: will schedule only if network status notifications are enabled in the Reachability instance.
// By default, they are not enabled.
[query scheduleOnRunLoop:[NSRunLoop currentRunLoop]];
SCNetworkReachabilityFlags flags;
BOOL gotFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
if (!gotFlags) {
return NO;
}
BOOL isReachable = [self isReachableWithoutRequiringConnection:flags];
// Callers of this method might want to use the reachability flags, so if an 'out' parameter
// was passed in, assign the reachability flags to it.
if (outFlags) {
*outFlags = flags;
}
return isReachable;
}
// Be a good citizen an unregister for network state changes when the application terminates.
- (void)stopListeningForReachabilityChanges
{
// Walk through the cache that holds SCNetworkReachabilityRefs for reachability
// queries to particular hosts or addresses.
NSEnumerator *enumerator = [self.reachabilityQueries objectEnumerator];
ReachabilityQuery *reachabilityQuery;
while (reachabilityQuery = [enumerator nextObject]) {
CFArrayRef runLoops = reachabilityQuery.runLoops;
NSUInteger runLoopCounter, maxRunLoops = CFArrayGetCount(runLoops);
for (runLoopCounter = 0; runLoopCounter < maxRunLoops; runLoopCounter++) {
CFRunLoopRef nextRunLoop = (CFRunLoopRef)CFArrayGetValueAtIndex(runLoops, runLoopCounter);
SCNetworkReachabilityUnscheduleFromRunLoop(reachabilityQuery.reachabilityRef, nextRunLoop, kCFRunLoopDefaultMode);
}
CFArrayRemoveAllValues(reachabilityQuery.runLoops);
}
}
/*
Create a SCNetworkReachabilityRef for hostName, which lets us determine if hostName
is currently reachable, and lets us register to receive notifications when the
reachability of hostName changes.
*/
- (SCNetworkReachabilityRef)reachabilityRefForHostName:(NSString *)hostName
{
if (!hostName || ![hostName length]) {
return NULL;
}
// Look in the cache for an existing SCNetworkReachabilityRef for hostName.
ReachabilityQuery *cachedQuery = [self.reachabilityQueries objectForKey:hostName];
SCNetworkReachabilityRef reachabilityRefForHostName = cachedQuery.reachabilityRef;
if (reachabilityRefForHostName) {
return reachabilityRefForHostName;
}
// Didn't find an existing SCNetworkReachabilityRef for hostName, so create one ...
reachabilityRefForHostName = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [hostName UTF8String]);
NSAssert1(reachabilityRefForHostName != NULL, #"Failed to create SCNetworkReachabilityRef for host: %#", hostName);
ReachabilityQuery *query = [[[ReachabilityQuery alloc] init] autorelease];
query.hostNameOrAddress = hostName;
query.reachabilityRef = reachabilityRefForHostName;
// If necessary, register for notifcations for the SCNetworkReachabilityRef on the current run loop.
// If an existing SCNetworkReachabilityRef was found in the cache, we can reuse it and register
// to receive notifications from it in the current run loop, which may be different than the run loop
// that was previously used when registering the SCNetworkReachabilityRef for notifications.
// -scheduleOnRunLoop: will schedule only if network status notifications are enabled in the Reachability instance.
// By default, they are not enabled.
[query scheduleOnRunLoop:[NSRunLoop currentRunLoop]];
// ... and add it to the cache.
[self.reachabilityQueries setObject:query forKey:hostName];
return reachabilityRefForHostName;
}
/*
Create a SCNetworkReachabilityRef for the IP address in addressString, which lets us determine if
the address is currently reachable, and lets us register to receive notifications when the
reachability of the address changes.
*/
- (SCNetworkReachabilityRef)reachabilityRefForAddress:(NSString *)addressString
{
if (!addressString || ![addressString length]) {
return NULL;
}
struct sockaddr_in address;
BOOL gotAddress = [self addressFromString:addressString address:&address];
// The attempt to convert addressString to a sockaddr_in failed.
if (!gotAddress) {
NSAssert1(gotAddress != NO, #"Failed to convert an IP address string to a sockaddr_in: %#", addressString);
return NULL;
}
// Look in the cache for an existing SCNetworkReachabilityRef for addressString.
ReachabilityQuery *cachedQuery = [self.reachabilityQueries objectForKey:addressString];
SCNetworkReachabilityRef reachabilityRefForAddress = cachedQuery.reachabilityRef;
if (reachabilityRefForAddress) {
return reachabilityRefForAddress;
}
// Didn't find an existing SCNetworkReachabilityRef for addressString, so create one ...
reachabilityRefForAddress = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (struct sockaddr *)&address);
NSAssert1(reachabilityRefForAddress != NULL, #"Failed to create SCNetworkReachabilityRef for address: %#", addressString);
ReachabilityQuery *query = [[[ReachabilityQuery alloc] init] autorelease];
query.hostNameOrAddress = addressString;
query.reachabilityRef = reachabilityRefForAddress;
// If necessary, register for notifcations for the SCNetworkReachabilityRef on the current run loop.
// If an existing SCNetworkReachabilityRef was found in the cache, we can reuse it and register
// to receive notifications from it in the current run loop, which may be different than the run loop
// that was previously used when registering the SCNetworkReachabilityRef for notifications.
// -scheduleOnRunLoop: will schedule only if network status notifications are enabled in the Reachability instance.
// By default, they are not enabled.
[query scheduleOnRunLoop:[NSRunLoop currentRunLoop]];
// ... and add it to the cache.
[self.reachabilityQueries setObject:query forKey:addressString];
return reachabilityRefForAddress;
}
- (NetworkStatus)remoteHostStatus
{
/*
If the current host name or address is reachable, determine which network interface it is reachable through.
If the host is reachable and the reachability flags include kSCNetworkReachabilityFlagsIsWWAN, it
is reachable through the carrier data network. If the host is reachable and the reachability
flags do not include kSCNetworkReachabilityFlagsIsWWAN, it is reachable through the WiFi network.
*/
SCNetworkReachabilityRef reachabilityRef = nil;
if (self.hostName) {
reachabilityRef = [self reachabilityRefForHostName:self.hostName];
} else if (self.address) {
reachabilityRef = [self reachabilityRefForAddress:self.address];
} else {
NSAssert(self.hostName != nil && self.address != nil, #"No hostName or address specified. Cannot determine reachability.");
return NotReachable;
}
if (!reachabilityRef) {
return NotReachable;
}
SCNetworkReachabilityFlags reachabilityFlags;
BOOL gotFlags = SCNetworkReachabilityGetFlags(reachabilityRef, &reachabilityFlags);
if (!gotFlags) {
return NotReachable;
}
BOOL reachable = [self isReachableWithoutRequiringConnection:reachabilityFlags];
if (!reachable) {
return NotReachable;
}
if (reachabilityFlags & ReachableViaCarrierDataNetwork) {
return ReachableViaCarrierDataNetwork;
}
return ReachableViaWiFiNetwork;
}
- (NetworkStatus)internetConnectionStatus
{
/*
To determine if the device has an Internet connection, query the address
0.0.0.0. If it's reachable without requiring a connection, first check
for the kSCNetworkReachabilityFlagsIsDirect flag, which tell us if the connection
is to an ad-hoc WiFi network. If it is not, the device can access the Internet.
The next thing to determine is how the device can access the Internet, which
can either be through the carrier data network (EDGE or other service) or through
a WiFi connection.
Note: Knowing that the device has an Internet connection is not the same as
knowing if the device can reach a particular host. To know that, use
-[Reachability remoteHostStatus].
*/
SCNetworkReachabilityFlags defaultRouteFlags;
BOOL defaultRouteIsAvailable = [self isNetworkAvailableFlags:&defaultRouteFlags];
if (defaultRouteIsAvailable) {
if (defaultRouteFlags & kSCNetworkReachabilityFlagsIsDirect) {
// The connection is to an ad-hoc WiFi network, so Internet access is not available.
return NotReachable;
}
else if (defaultRouteFlags & ReachableViaCarrierDataNetwork) {
return ReachableViaCarrierDataNetwork;
}
return ReachableViaWiFiNetwork;
}
return NotReachable;
}
- (NetworkStatus)localWiFiConnectionStatus
{
SCNetworkReachabilityFlags selfAssignedAddressFlags;
/*
To determine if the WiFi connection is to a local ad-hoc network,
check the availability of the address 169.254.x.x. That's an address
in the self-assigned range, and the device will have a self-assigned IP
when it's connected to a ad-hoc WiFi network. So to test if the device
has a self-assigned IP, look for the kSCNetworkReachabilityFlagsIsDirect flag
in the address query. If it's present, we know that the WiFi connection
is to an ad-hoc network.
*/
// This returns YES if the address 169.254.0.0 is reachable without requiring a connection.
BOOL hasLinkLocalNetworkAccess = [self isAdHocWiFiNetworkAvailableFlags:&selfAssignedAddressFlags];
if (hasLinkLocalNetworkAccess && (selfAssignedAddressFlags & kSCNetworkReachabilityFlagsIsDirect)) {
return ReachableViaWiFiNetwork;
}
return NotReachable;
}
// Convert an IP address from an NSString to a sockaddr_in * that can be used to create
// the reachability request.
- (BOOL)addressFromString:(NSString *)IPAddress address:(struct sockaddr_in *)address
{
if (!IPAddress || ![IPAddress length]) {
return NO;
}
memset((char *) address, sizeof(struct sockaddr_in), 0);
address->sin_family = AF_INET;
address->sin_len = sizeof(struct sockaddr_in);
int conversionResult = inet_aton([IPAddress UTF8String], &address->sin_addr);
if (conversionResult == 0) {
NSAssert1(conversionResult != 1, #"Failed to convert the IP address string into a sockaddr_in: %#", IPAddress);
return NO;
}
return YES;
}
#end
#interface ReachabilityQuery ()
- (CFRunLoopRef)startListeningForReachabilityChanges:(SCNetworkReachabilityRef)reachability onRunLoop:(CFRunLoopRef)runLoop;
#end
#implementation ReachabilityQuery
#synthesize reachabilityRef = _reachabilityRef;
#synthesize runLoops = _runLoops;
#synthesize hostNameOrAddress = _hostNameOrAddress;
- (id)init
{
self = [super init];
if (self != nil) {
self.runLoops = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
}
return self;
}
- (void)dealloc
{
CFRelease(self.runLoops);
[super dealloc];
}
- (BOOL)isScheduledOnRunLoop:(CFRunLoopRef)runLoop
{
NSUInteger runLoopCounter, maxRunLoops = CFArrayGetCount(self.runLoops);
for (runLoopCounter = 0; runLoopCounter < maxRunLoops; runLoopCounter++) {
CFRunLoopRef nextRunLoop = (CFRunLoopRef)CFArrayGetValueAtIndex(self.runLoops, runLoopCounter);
if (nextRunLoop == runLoop) {
return YES;
}
}
return NO;
}
- (void)scheduleOnRunLoop:(NSRunLoop *)inRunLoop
{
// Only register for network state changes if the client has specifically enabled them.
if ([[Reachability sharedReachability] networkStatusNotificationsEnabled] == NO) {
return;
}
if (!inRunLoop) {
return;
}
CFRunLoopRef runLoop = [inRunLoop getCFRunLoop];
// Notifications of status changes for each reachability query can be scheduled on multiple run loops.
// To support that, register for notifications for each runLoop.
// -isScheduledOnRunLoop: iterates over all of the run loops that have previously been used
// to register for notifications. If one is found that matches the passed in runLoop argument, there's
// no need to register for notifications again. If one is not found, register for notifications
// using the current runLoop.
if (![self isScheduledOnRunLoop:runLoop]) {
CFRunLoopRef notificationRunLoop = [self startListeningForReachabilityChanges:self.reachabilityRef onRunLoop:runLoop];
if (notificationRunLoop) {
CFArrayAppendValue(self.runLoops, notificationRunLoop);
}
}
}
// Register to receive changes to the 'reachability' query so that we can update the
// user interface when the network state changes.
- (CFRunLoopRef)startListeningForReachabilityChanges:(SCNetworkReachabilityRef)reachability onRunLoop:(CFRunLoopRef)runLoop
{
if (!reachability) {
return NULL;
}
if (!runLoop) {
return NULL;
}
SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
SCNetworkReachabilitySetCallback(reachability, ReachabilityCallback, &context);
SCNetworkReachabilityScheduleWithRunLoop(reachability, runLoop, kCFRunLoopDefaultMode);
return runLoop;
}
#end
Found a good way to solve this. The code is from Xamarin/Mono, so translate the syntax to objective-c if that is what you are using.
CTTelephonyNetworkInfo netInfo = new CTTelephonyNetworkInfo ();
string currentRadio = netInfo.CurrentRadioAccessTechnology;
If your phone does not have mobile coverage or is in airplane mode "currentRadio" will be null. This also works if you have Wifi or other network access but no mobile connection, so it works perfectly for OP's usecase (which was the same as mine)
The canOpenURL: will test if there is an application that can handle the tel: URL, but that you probably already knew.
You most likely cannot detect if a user has sufficient funds on his calling account to actually place calls (i.e. no credit on a prepaid card), but I think it's highly unlikely you want to know that ;-)
Can't you assume you can place calls if there is an Wireless Wide Area Network (WWAN) connection? You can test for WWAN availability using the Reachability example.