Is it possible to detect if the cellular network is available? - iphone

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.

Related

iPhone iOS how to publish a UDP service?

I'm modifying the "Chatty" app from here: http://mobileorchard.com/tutorial-networking-and-bonjour-on-iphone/
I'm trying to create a server which quickly receives information from multiple clients, but does not really send anything back. There are both Wifi and Bluetooth used at the same time, so I would like to maximize the network throughput. I think that UDP protocol might be faster, because there's no handshaking/packet sequence verification.
Is changing the "_chatty._tcp." to "_chatty._udp." enough in this example? I checked the documentation for NSNetService, but don't see anything about UDP there.
- (BOOL) publishService {
// come up with a name for our chat room
NSString* chatRoomName = [NSString stringWithFormat:#"%#'chat room", [[AppConfig getInstance] name]];
// create new instance of netService
self.netService = [[NSNetService alloc]
initWithDomain:#"" type:#"_chatty._tcp."
name:chatRoomName port:self.port];
if (self.netService == nil)
return NO;
// Add service to current run loop
[self.netService scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSRunLoopCommonModes];
// NetService will let us know about what's happening via delegate methods
[self.netService setDelegate:self];
// Publish the service
[self.netService publish];
return YES;
}
// Start browsing for servers
- (BOOL)start {
// Restarting?
if ( netServiceBrowser != nil ) {
[self stop];
}
netServiceBrowser = [[NSNetServiceBrowser alloc] init];
if( !netServiceBrowser ) {
return NO;
}
netServiceBrowser.delegate = self;
[netServiceBrowser searchForServicesOfType:#"_chatty._tcp." inDomain:#""];
return YES;
}
It appears that the app is working fine after changing "_chatty._tcp." to "_chatty._udp."

Run Internet Connection Check Throughout Entire App

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;
}

Can I determine / how, if a device has vibration or not?

I have some settings that enable/disable vibration for certain actions, but I find it pointless to display them if the device doesn't have the ability to vibrate. Is there a way to check if the person is using an iPod touch and if it has vibration?
I'm not sure there is a way to do this other than doing model checks which is probably not a great approach. I do know that apple provides:
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
If the device can vibrate, it will. On devices without vibration, it will do nothing. There is another call:
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
This one will vibrate the device if it hash the capability or the device will beep.
It might be better to just have the settings and have some explanation around the setting because a user may want the beep when they do not have a vibrating device. Maybe call the setting something other than "Vibration Alert On/Off".
This code should do it - be aware it 'assumes' the iPhone is the only device with Vibration capability. Which it is for the moment...
- (NSString *)machine
{
static NSString *machine = nil;
// we keep name around (its like 10 bytes....) forever to stop lots of little mallocs;
if(machine == nil)
{
char * name = nil;
size_t size;
// Set 'oldp' parameter to NULL to get the size of the data
// returned so we can allocate appropriate amount of space
sysctlbyname("hw.machine", NULL, &size, NULL, 0);
// Allocate the space to store name
name = malloc(size);
// Get the platform name
sysctlbyname("hw.machine", name, &size, NULL, 0);
// Place name into a string
machine = [[NSString stringWithUTF8String:name] retain];
// Done with this
free(name);
}
return machine;
}
-(BOOL)hasVibration
{
NSString * machine = [self machine];
if([[machine uppercaseString] rangeOfString:#"IPHONE"].location != NSNotFound)
{
return YES;
}
return NO;
}
Just edited to stop the machine call from doing lots of small mallocs each time its called.

DNS resolution with IPv6 on iOS only synchronous?

(This is a work in progress. I wonder if someone could to improve it)
in Objective C, it's easy to resolve a hostname with NSHost.
[[NSHost hostWithName:#"www.google.com"] address]
Sadly iOS (iPhone) contains only a private version of NSHost.
I found many ways of doing this with other Objects or methods, but all of them got only IPv4 addresses in the results. So here is for the moment the only efficient method I have found.
I first tried to use the asynchronous CFHostStartInfoResolution as did bdunagan, but failed to adapt it to IPv6.
Some of you will appreciate to get a method working, so here is one, but if you know a way which would be Asynchronous I would appreciate to learn about it... cause for the moment I use a Popup to alert about the next freeze that could occur with slow cellular connection
/**
Give the IPs corresponding to a Hostname
Sometime only 1 IPv4 is shown even if there's more.
Sometime only 1 IPv6 is shown even if there's more.
Certainly due to iOS Memory optimisation when locally cached
#author Christian Gonzalvez, http://wiki.gonzofamily.com
#param hostName A hostname
#return an Array of NSString of all the corresponding IP addresses. The first
is the Canonical name, the following are IPs (all NSString)
*/
+ (NSArray *)addressesForHostname:(NSString *)hostname
{
const char* hostnameC = [hostname UTF8String];
struct addrinfo hints, *res;
struct sockaddr_in *s4;
struct sockaddr_in6 *s6;
int retval;
char buf[64];
NSMutableArray *result; //the array which will be return
NSMutableArray *result4; //the array of IPv4, to order them at the end
NSString *previousIP = nil;
memset (&hints, 0, sizeof (struct addrinfo));
hints.ai_family = PF_UNSPEC;//AF_INET6;
hints.ai_flags = AI_CANONNAME;
//AI_ADDRCONFIG, AI_ALL, AI_CANONNAME, AI_NUMERICHOST
//AI_NUMERICSERV, AI_PASSIVE, OR AI_V4MAPPED
retval = getaddrinfo(hostnameC, NULL, &hints, &res);
if (retval == 0)
{
if (res->ai_canonname)
{
result = [NSMutableArray arrayWithObject:[NSString stringWithUTF8String:res->ai_canonname]];
}
else
{
//it means the DNS didn't know this host
return nil;
}
result4= [NSMutableArray array];
while (res) {
switch (res->ai_family){
case AF_INET6:
s6 = (struct sockaddr_in6 *)res->ai_addr;
if(inet_ntop(res->ai_family, (void *)&(s6->sin6_addr), buf, sizeof(buf))
== NULL)
{
NSLog(#"inet_ntop failed for v6!\n");
}
else
{
//surprisingly every address is in double, let's add this test
if (![previousIP isEqualToString:[NSString stringWithUTF8String:buf]]) {
[result addObject:[NSString stringWithUTF8String:buf]];
}
}
break;
case AF_INET:
s4 = (struct sockaddr_in *)res->ai_addr;
if(inet_ntop(res->ai_family, (void *)&(s4->sin_addr), buf, sizeof(buf))
== NULL)
{
NSLog(#"inet_ntop failed for v4!\n");
}
else
{
//surprisingly every address is in double, let's add this test
if (![previousIP isEqualToString:[NSString stringWithUTF8String:buf]]) {
[result4 addObject:[NSString stringWithUTF8String:buf]];
}
}
break;
default:
NSLog(#"Neither IPv4 nor IPv6!");
}
//surprisingly every address is in double, let's add this test
previousIP = [NSString stringWithUTF8String:buf];
res = res->ai_next;
}
}else{
NSLog(#"no IP found");
return nil;
}
return [result arrayByAddingObjectsFromArray:result4];
}
NB: I noticed that most of the time only 1 IPv6 is returned, I suspect it's due to iOS Memory optimisation when locally cached. if you run this method again and again, sometime you have 3 IPv6, but then you have only 1 IPv4.
If you want a method to run on a background thread, the simplest way is to use performSelectorInBackground:withObject:; this is an instance method of NSObject, so any object can use it without any extra work (including, interestingly enough, class objects, which is good in this case because this is a class method):
[[self class] performSelectorInBackground:#selector(addressesForHostName:)
withObject:theHostName];
Inside the method, you will need to set up an autorelease pool for the thread. You will also need some kind of callback method set up to get the return value back to your main thread. Make sure that you don't try to do any GUI activity on the background thread. It's only safe to do that on the main thread.
+ (NSArray *)addressesForHostname:(NSString *)hostname
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// Do your stuff...
// Wait until done to allow memory to be managed properly
// If we did not do this, the array might be deallocated
// before the main thread had a chance to retain it
[self performSelectorOnMainThread:#selector(addressesCallback:)
withObject:[result arrayByAddingObjectsFromArray:result4]
waitUntilDone:YES];
// Inside a class method, self refers to the class object.
[pool drain];
}
If you were not on the main thread to begin with, or if you needed more control, you could also look into NSOperation, which is more powerful and therefore requires more work. It's still easier than explicit thread management, though!
Hope that solves your problem. It sounded like you have this method doing what you need, you just need it to not block the main thread.
thanks to Josh I could do it, but here is what I had to do :
Instead of calling directly
self.ipAddressesString = [CJGIpAddress addressesForHostname:#"www.google.com"];
I call
[self resolveNow:#"www.google.com"];
And create 3 new methods:
- (void)resolveNow:(NSString *)hostname
{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
[self performSelectorInBackground:#selector(hostname2ipAddresses:)
withObject:hostname];
}
- (void)hostname2ipAddresses:(NSString *)hostname
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
//Here is my previous lonely line !! safely started in an other thread
self.ipAddressesString = [CJGIpAddress addressesForHostname:hostname];
[self performSelectorOnMainThread:#selector(resolutionDidFinish)
withObject:nil
waitUntilDone:YES];
[pool drain];
}
- (void)resolutionDidFinish
{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
//My STUFF with self.ipAddressesString (now filled)
}
Edit:
In practice I use all of that in a Model, so I had a crash when I close the View before the end of the resolution
So in the view I added in dealloc what is necessary to avoid a crash
- (void)dealloc
{
self.model.delegate = nil;
[super dealloc];
}
Then - in the model - I test delegate before doing anything with it.

How do I access my application's state (classes, properties, etc.) upon a callback from CFStream?

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!