Using Reachability for Internet *or* local WiFi? - iphone

I've searched SO for the answer to this question, and it's not really addressed, at least not to a point where I can make it work.
I was originally only checking for Internet reachability, using:
self.wwanReach = [Reachability reachabilityWithHostName:#"www.apple.com"];
[wwanReach startNotifer];
I now need to support a local WiFi connection (in the absence of reaching the Internet in general), and when I found +reachabilityForLocalWiFi, I also noticed there was +reachabilityForInternetConnection. I figured I could use these, instead of hard-coding "www.apple.com" in there, but alas, when I use:
self.wwanReach = [Reachability reachabilityForInternetConnection];
[wwanReach startNotifer];
self.wifiReach = [Reachability reachabilityForLocalWiFi];
[wifiReach startNotifer];
the reachability callback that I've set up "never" gets called, for values of "never" up to 10, 12, 15 minutes or so (which was as long as my patience lasted. (User's patience will be much less, I'm sure.) Switching back to +reachabilityWithHostName: works within seconds. I also tried each "pair" individually, in case there was an issue with two notifiers in progress simultaneously, but that made no difference.
So: what is the appropriate way to determine reachability to either the Internet/WWAN or a local Wifi network (either one, or both)?
[This particular use case is an iPhone or iPad connecting to a Mac mini computer-to-computer network; I'm sure other situations apply.]

Use this function to check if wifi is on
- (BOOL)isWifiOn {
Reachability* wifiReach = [Reachability reachabilityForLocalWiFi];
NetworkStatus netStatus = [wifiReach currentReachabilityStatus];
return (netStatus==ReachableViaWiFi);
}
similar code can be used to check reachabilityForInternetConnection but you have to check
(netStatus==ReachableViaWiFi)
if you care that it's over wifi AND
(netStatus==ReachableViaWWAN)
if you care that it's over WWAN

I ran int the same problem. What I found in the end is that for WWAN or WiFi reachability, the notification callback is only called when there is a network change.
In other words, check the current reachability immediately after you create the reachability object. Do not wait for the notification, because the notification will only be posted when next network change happens.
For Internet/WWAN:
self.wwanReach = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [wwanReach currentReachabilityStatus];
if (networkStatus == ReachableViaWWAN) {
// do something
}
For WiFi:
self.wifiReach = [Reachability reachabilityForLocalWiFi];
NetworkStatus networkStatus = [wifiReach currentReachabilityStatus];
if (networkStatus == ReachableViaWiFi) {
// do something
}

The reachability example from apple shows you how to use a notification, which is an event push model and supposed to be efficient, but I found that the notifications weren't always working properly for me. Sometimes they wouldn't fire, other times they would provide wrong information. So I ended up polling with a 2 second repeating timer, and checking for wifi with a procedure like the one described by stinkbutt above. Here's a good reference for timer implementation.

I'm not sure if this is your problem, but I noticed that it matters when you call startNotifier. I was having a similar problem with never receiving notifications (but with shorter values for "never" -- I guess I'm not as paitent) until I moved the startNotifier call into some UI code, specifically applicationDidFinishLaunching.

Related

Reachability Runtime error - SCNetworkReachabilitySetDispatchQueue() failed: Permission denied

Here is my code:
Reachability *r = [Reachability reachabilityWithHostname:host];
r.reachableBlock = ^(Reachability*reach)
{
// Update the UI on the main thread
});
};
r.unreachableBlock = ^(Reachability*reach)
{
// Update the UI on the main thread with error alert
});
};
[r startNotifier];
Upon running the last statement, I get following error logged, and it never executes any of the reachableBlock or unreachableBlock.
SCNetworkReachabilitySetDispatchQueue() failed: Permission denied
For anyone wanting to know what I tried already, I also attempted this:
dispatch_async(dispatch_get_global_queue(0,0), ^{
[r startNotifier];
});
But this yields same result.
I logged an issue here.
This is no longer an issue.
By some mysterious reasons, I cleaned up build folder, reset iOS simulator, relaunched it and recompiled - and the error is gone. I didn't succeed following these steps at first, but doing them just for the sake of trying, and it worked!

Accurately reading of iPhone signal strength

There are a few questions on this already, but nothing in them seems to provide accurate results. I need to determine simply if the phone is connected to a cell network at a given moment.
http://developer.apple.com/library/ios/#documentation/NetworkingInternet/Reference/CTCarrier/Reference/Reference.html
This class seems to be documented incorrectly, returning values for mobileCountryCode, isoCountryCode and mobileNetworkCode where no SIM is installed to the phone. carrierName indicates a 'home' network or a previous home network if the phone has been unlocked.
I also looked up and found some people claiming the following to work, which uses an undocumented method of the CoreTelephony framework, but the results have been useless to me, reporting seemingly random figures, where perhaps it is not itself updating consistently.
-(int) getSignalStrength
{
void *libHandle = dlopen("/System/Library/Frameworks/CoreTelephony.framework/CoreTelephony", RTLD_LAZY);
int (*CTGetSignalStrength)();
CTGetSignalStrength = dlsym(libHandle, "CTGetSignalStrength");
if( CTGetSignalStrength == NULL) NSLog(#"Could not find CTGetSignalStrength");
int result CTGetSignalStrength();
dlclose(libHandle);
return result;
}
Thanks.
Edit: The app is connected to an internal wifi and must remain so, making a reachability check more difficult.
I'm playing with this function and I've noticed you're calling it in an interesting way. I'm calling it by adding CoreTelephony.framework as a compile-time link. For the function itself, you'll want to declare it's prototype somewhere (perhaps immediately above the method you call from):
int CTGetSignalStrength();
This needs to be declared since it isn't in a public header for CoreTelephony.
Now, I built a simple app that prints signal strength every second.
int CTGetSignalStrength();
- (void)viewDidLoad
{
[super viewDidLoad];
while (true) {
printf("signal strength: %d\n", CTGetSignalStrength());
sleep(1);
}
}
I ran it on my iPad mini and it shows steady values until I picked it up, where the number went up. Wrapping my iPad in tin foil (tin foil is a debugging tool I have never used before) caused the number to go down. When I put my iPad in airplane mode, it kept repeating the last value, so this will not be an accurate measure for you.
If you want to test if a device currently has a cellular data network connection, you may be more interested in Reachability, specifically kSCNetworkReachabilityFlagsIsWWAN.
Ok I think I have the correct solution now, which was a bit simpler in the end.
The issue with the CTGetSignalStrength() method is that it works normally, but if you remove a sim, it reports the last signal before the removal. I found another method in the same framework called CTSIMSupportGetSIMStatus(), also undocumented, which can tell you if a SIM is currently connected. Using both as follows should confirm the current network signal.
First declare the methods:
NSString * CTSIMSupportGetSIMStatus();
int CTGetSignalStrength();
Then check connectivity to cell network like so:
NSString *status = CTSIMSupportGetSIMStatus();
int signalstrength = CTGetSignalStrength();
BOOL connected = ( [status isEqualToString: #"kCTSIMSupportSIMStatusReady"] && signalstrength > 0 );

How to set VoIP mode on a socket in iOS 4

I'm trying to set up a socket in VoIP mode on an iPhone, so that my app can be woken when an event happens. I have a simple server that will write to the socket if and only if the app should wake up and talk to the main web service about something. Calling
CFReadStreamSetProperty()
on the stream attached to the socket always seems to return zero, which if I'm not mistaken is FALSE, meaning the stream did not recognize and/or accept the property value. I read in a previous question that this facility is not available on the simulator, so I tried it on a real phone, with the same result.
How can I figure out why the call is failing?
The code is below:
- (id) init {
NSLog(#"NotificationClient init, host = %#", [self getNotificationHostName]);
CFHostRef notificationHost = CFHostCreateWithName(kCFAllocatorDefault, (CFStringRef)[self getNotificationHostName]);
CFStreamCreatePairWithSocketToCFHost(kCFAllocatorDefault, notificationHost, [self getNotificationPort], &_fromServer, &_toServer);
BOOL status;
status = CFReadStreamOpen(_fromServer);
status = CFReadStreamSetProperty(_fromServer, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
NSLog(#"status from setting VoIP mode on socket is %d", status);
status = CFWriteStreamOpen(_toServer);
[self sendMessage:#"STRT" withArgument:#"iPhone"];
[self startReceivingMessages];
return self;
}
Hmm... it looks like there were two problems. First, you need to set the property before opening the stream. And second, it looks like it only works if you are on the main thread when you do this.

Game Center Multiplayer using GKMatch but seems can't be connected

Hi I'm a new bie in Game Center for iOS. I'm trying to add the multiplayer feature using matches to my game and following the documentation.
So far I reached a point where 2 of my clients can successfully get a match, i.e. the matchmakerViewController:didFindMatch callback is called and a GKMatch object is delivered.
However after that I seems to be stuck there forever, because according to the documentation, I'll have to wait until all the players (2 in my case) are actually connected before starting my game. But it seems the match:player:didChangeState callback is never called to indicate a successful connection. Well, I'm sure my clients are all in the same wifi network ( or is it a must?) Could any one enlighten me on this case? Do I have to do any extra things to make the clients to connect? Thanks a lot for the help!
So I was running into this and the solution (for me) was somewhat embarrasing. I had copied and pasted a bunch of the code from the Apple docs..and they left out an obvious step. They never actually set the match's delegate!
My code now is:
- (void)matchmakerViewController:(GKMatchmakerViewController *)viewController didFindMatch:(GKMatch *)match {
[self dismissModalViewControllerAnimated:YES];
self.myMatch = match; // Use a retaining property to retain the match.
self.myMatch.delegate = self; // THIS LINE WAS MISSING IN THE APPLE DOCS. DOH.
// Start the game using the match.
NSLog(#"Match started! Expected Player Count:%d %#",match.expectedPlayerCount, match.playerIDs);}
Once I actually set the match delegate, the functions get called. Doh.
When you get the GKMatch object, be sure to check the expectedPlayerCount property. It is possible that the other player is already connected, and thus you will not get a match:player:didChangeState on the delegate.
I have had the same problem with a friend. The solution was quite strange but it works afterwards. On all devices you have to enable the Notifications (Sounds/Alerts/Badges) for the Game Center inside the Settings/Notifications options. Afterwards we could establish a connection and did receive a match object
Inside your callback matchmakerViewController:didFindMatch
Add this code then you'll see the callback "match:player:didChangeState" being called by GC
GKMatchRequest *request = [[[GKMatchRequest alloc] init] autorelease];
request.minPlayers = 2;
request.maxPlayers = 2;
[[GKMatchmaker sharedMatchmaker] addPlayersToMatch:match matchRequest:request completionHandler:^(NSError* error) {
if(error)
NSLog(#"Error adding player: %#", [error localizedDescription]);
}];
It was working all along. The only difference is that... when you use invites the event "didChangeState" doensn't get called. You're connected without notice and you can start to receive data. I never tried to send/receive data... cuz i was expecting the event first, but i did send something by mistake one time, and it worked. :)
- (void)matchmakerViewController:(GKMatchmakerViewController *)viewController didFindMatch:(GKMatch *) match {
//Dismiss window
[self dismissModalViewControllerAnimated:YES];
//Retain match
self.myMatch = match;
//Delegate
myMatch.delegate = self;
//Flag
matchStarted = TRUE;
//Other stuff
}
- (void)match:(GKMatch *)match player:(NSString *)playerID didChangeState:(GKPlayerConnectionState)state {
//This code gets called only on auto-match
}
The above code works as expected.
Make sure that you've set your class as the delegate for GKSession. The class will need to implement the GKSessionDelegate protocol... otherwise, it'll never receive this callback. Here's the protocol reference. Hope this helps!

Why does Reachability sample app stall here?

Apple's sample app named Reachability shows how to detect connections. If you have only wifi but not internet, the app stalls for over a minute on the second line below:
SCNetworkReachabilityFlags reachabilityFlags;
BOOL gotFlags = SCNetworkReachabilityGetFlags(reachabilityRef, &reachabilityFlags);
SCNetworkReachabilityGetFlags comes from SystemConfiguration.framework. Any suggestions on how to get around this?
To answer your question directly, no, there doesn't seem to be any way to "get around" SCNetworkReachabilityGetFlags() taking a long time to return under the specific circumstances you described (e.g., checking remote host reachability via WiFi connection to a router with no Internet). A couple of options:
OPTION 1. Make the call in a separate thread so that the rest of your app can keep running. Modify ReachabilityAppDelegate.m as follows for an example:
// Modified version of existing "updateStatus" method
- (void)updateStatus
{
// Query the SystemConfiguration framework for the state of the device's network connections.
//self.remoteHostStatus = [[Reachability sharedReachability] remoteHostStatus];
self.remoteHostStatus = -1;
self.internetConnectionStatus = [[Reachability sharedReachability] internetConnectionStatus];
self.localWiFiConnectionStatus = [[Reachability sharedReachability] localWiFiConnectionStatus];
[tableView reloadData];
// Check remote host status in a separate thread so that the UI won't hang
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSTimer *timer = [NSTimer timerWithTimeInterval:0 target:self selector:#selector(updateRemoteHostStatus) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
[pool release];
}
// New method
- (void) updateRemoteHostStatus
{
self.remoteHostStatus = [[Reachability sharedReachability] remoteHostStatus];
[tableView reloadData];
}
OPTION 2. Use a different API/function that uses a timeout value when trying to connect to the remote host. That way your app would only hang for X seconds before it gives up.
Some other things to note:
The specific call to SCNetworkReachabilityGetFlags() that you're asking about (i.e., line ~399 in Reachability.m) is trying to see if www.apple.com is "reachable" to deduce if "the external internet" is "reachable" in general.
In Apple's System Config framework "reachable" might not mean what you think it does. According to the official docs, "reachable" seems to mean that, in theory, your computer could connect to host X if it wanted to, but it might need to actually establish a connection first (e.g., dial a modem first). In other words, SCNetworkReachabilityGetFlags() doesn't actually establish a connection.