I'm working on an app the uses the Multipeer Conectivity Framework. So far everything is going great, I've implemented programmatic browsing and invitations.
My issue is when the user accepts the invitation the Browser is not receiving the state change - thereby not creating the session.
This is the advertiser did receive invitation method i have created using an action sheet integrated with blocks.
- (void)advertiser:(MCNearbyServiceAdvertiser *)advertiser
didReceiveInvitationFromPeer:(MCPeerID *)peerID
withContext:(NSData *)context
invitationHandler:(void(^)(BOOL accept, MCSession *session))invitationHandler
{
[UIActionSheet showInView:self.view
withTitle:[[NSString alloc]initWithFormat:#"%# would like to share %# information with you.",peerID.displayName, (NSString *)context]
cancelButtonTitle:#"Cancel"
destructiveButtonTitle:#"Deny"
otherButtonTitles:#[#"Accept"]
tapBlock:^(UIActionSheet *actionSheet, NSInteger buttonIndex) {
NSLog(#"%i",buttonIndex==1?true:false);
MCSession *newSession=[[MCSession alloc]initWithPeer:[[MCPeerID alloc] initWithDisplayName:#"CRAP23456"]];
[newSession setDelegate: self];
NSLog(#"button index %i ",buttonIndex==1?true:false);
invitationHandler(buttonIndex==1?YES:NO,newSession);
}];
}
The above method is being called and the invitation handler is returning the correct value.
My implementation from the browser side is very simple - and this is the method that should be called when the user either accepts/declines the method. However, it's only being called when the user declines the invite:
- (void)session:(MCSession *)session peer:(MCPeerID *)peerID didChangeState:(MCSessionState)state
{
NSLog(#"%d",state);
NSLog(#"%ld",(long)MCSessionStateConnected);
}
Thanks in advance.
James.
I hope one of these will help:
Implement session:didReceiveCertificate:fromPeer:certificateHandler:
I read here that this is necessary.
Keep browsing and advertising between two peers a one-way deal; that is, don't accept invitations on both ends if both are browsing as well (at least don't accept an invitation and pass same session you're browsing with in invitationHandler()).
Wrap your code in the didChangeState in a block like this:
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"%d",state);
NSLog(#"%ld",(long)MCSessionStateConnected);
});
I ran into this issue too. My code on the browser side looked like this:
MCSession *session = [[MCSession alloc] initWithPeer:[self peerID]];
session.delegate = self;
[browser invitePeer:peerID toSession:session withContext:nil timeout:30.0f];
The issue with this is that the browser does not retain a reference to the session and so ARC comes around and cleans it up before the other end had the opportunity to accept.
Changing it to the following fixed the issue:
_session = [[MCSession alloc] initWithPeer:[self peerID]];
_session.delegate = self;
[browser invitePeer:peerID toSession:_session withContext:nil timeout:30.0f];
.. where _session is an ivar on my class.
HTH
I've been working on this project for a while, but I've encountered a problem that I can't figure out.
First, I have a checkbox button that saves to NSDefaultUser as BOOL value. It simply saves the value YES when it's pressed once and it saves NO if pressed again and so on... This checkbox button works fine like a normal custom checkbox button would.
I would like to make an option to mute all of my sounds in my app by using this checkbox button.
I'm playing my sounds by calling method such as:
- (void)startMusic1
{
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/music1.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
AVAudioPlayer *audioPlayer;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1;
if (audioPlayer == nil)
NSLog(#"Error: %#", [error description]);
else
[audioPlayer play];
}
So for every sound I want to play in my app, I could repeat something like:
- (IBAction)playButton:(id)sender
{
NSUserDefaults *default = [NSUserDefaults standardUserDefaults];
if(![default boolForKey:#"isMuted"])
{
[self startMusic1];
}
}
But, this gets repetitive especially because I have to manage a lot of different sounds (and different buttons that play sounds) for my project, and it seems irrelevant to repeat these steps.
I tried making a new class with a subclass of AVAudioPlayer and messed around with -(BOOL)play method for a few days, but I couldn't manage to get the results I wanted. I researched and found posts like Disable in App sounds but this still wouldn't do it.
I'm pretty new to programming overall, so it'll be great if someone could enlighten me a little.
I tackle this (rightly or wrongly, but it works for me) by using a global model singleton. This is a class that effectively maintains state across the entire application.
The way to do that is with a class that has a shared static property like this:
//// Interface
#import <Foundation/Foundation.h>
#interface AudioModel
#property (nonatomic) BOOL playAudio;
+(id)sharedInstance;
#end
//// Implementation
#import "AudioModel.h"
#implementation AudioModel
// property for toggling audio on or off
#synthesize playAudio = _playAudio;
// singleton model variable
static AudioModel* audio = nil;
-(BOOL)playAudio {
return _playAudio;
}
-(void)setPlayAudio:(BOOL)playAudio {
_playAudio = playAudio;
}
// static
+(AudioModel*)sharedInstance {
if(audio == nil)
{
audio = [[AudioModel alloc]init];
}
return audio;
}
-(AudioModel*)init {
self = [super init];
if(self){
// set up default sounds on
// this may read from your stored value
_playAudio = YES;
}
}
#end
Then when you want to read or write to this globally available singleton model, you set a variable in your controller like this:
AudioModel *volumeControl = [AudioModel sharedInstance];
if(volumeControl.playAudio){
// method to play audio passing audio file name...
}
You could also have a reference to your AVAudioPlayer instance in this class, init it on creation of the shared instance and pass files to it to play when required.
(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.
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!
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.