Why does Reachability sample app stall here? - iphone

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.

Related

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!

iPhone Socket gets closed unexpected

Well at least unexpected for me... This is the situation:
I open a Socket using the following code:
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (CFStringRef)ipaddress , 3333,&readStream, &writeStream);
if(!CFReadStreamOpen(readStream) || !CFWriteStreamOpen(writeStream))
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Connection error"
message:#"There has been a connection error, please ensure your internet connection is working"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
return;
}
This all goes fine, next thing I do is setup a callback:
CFStreamClientContext ctxt = {0,(void*)NULL,NULL,NULL,NULL};
static const CFOptionFlags kReadNetworkEvents = kCFStreamEventEndEncountered |
kCFStreamEventErrorOccurred |
kCFStreamEventHasBytesAvailable |
kCFStreamEventOpenCompleted |
kCFStreamEventNone;
CFReadStreamSetClient(readStream, kReadNetworkEvents, ReadStreamClientCallBack, &ctxt);
CFReadStreamScheduleWithRunLoop(readStream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
Also works fine, I'll list the callback method to be complete:
static void ReadStreamClientCallBack( CFReadStreamRef stream, CFStreamEventType type, void *clientCallBackInfo ) {
switch (type)
{
case kCFStreamEventEndEncountered:
{
break;
}
case kCFStreamEventErrorOccurred:
break;
case kCFStreamEventHasBytesAvailable:
{
[this stopListen];
UInt8 buffer[1024];
int count = CFReadStreamRead(stream, buffer, 1024);
CFStreamStatus status = CFReadStreamGetStatus(this.readStream);
CFErrorRef error = CFReadStreamCopyError (this.readStream);
CFStringRef errorCode = CFErrorCopyDescription(error);
// Bunch of other irrelevant code
Now what goes wrong: All this code works perfectly fine as long as I'm staying in the application, even if I exit the application and enter it again it works still fine. If I enter standby while the application is open it also works fine. However if I exit the application, put my phone on standby, get my phone out of standby and reenter the application, the call back immediatly gets called, with eventtype kCFStreamEventHasBytesAvailable, even though I'm 100% sure no bytes have been send. If I then call CFReadStreamRead it returns -1 to me, since this means an error occured I figured out the error code which is 57, this mean that the socket has been closed.
Am I overlooking a certain aspect of socket programming on the iPhone? I must admit I'm new to it. Is it not possible to keep a TCP Socket open while out of the application (and entering standby)?
I have tried to call CFReadStreamOpen again which returned false to me.
I'm lost here, please help!
Thanks in advance
Part of the multi-tasking features in 4.0+ require extra coding to support keeping connections alive and performing tasks in the background. You are probably just a victim of the OS taking back those resources since you didn't "opt-in" for them at the appropriate time.
This section covers the basics of backgrounding:
http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html
Specifically this:
Be prepared to handle connection
failures in your network-based
sockets. The system may tear down
socket connections while your
application is suspended for any
number of reasons. As long as your
socket-based code is prepared for
other types of network failures, such
as a lost signal or network
transition, this should not lead to
any unusual problems. When your
application resumes, if it encounters
a failure upon using a socket, simply
reestablish the connection.
However, there are three very special things that you can do in the background, and if you do you should declare them in your Info.plist to be a good App citizen. These three values are in the UIBackgroundModes property and they are audio location and voip
You can request more time for your task by registering a block (even though it isn't guarunteed you'll get it) like this:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UIApplication* app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
// Start the long-running task and return immediately.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Do the work associated with the task.
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
});
}
See also A Short Practical Guide to Blocks for a quick overview and the Concurrency Programming Guide for more detailed information.

How can I get notified when it reaches a certain time of day in an iPhone application?

I am working on an application that needs a method to be called at a certain time (15 minutes past the hour to be exact). Is there a way to make this happen without consuming a ton of CPU and battery life? I've tried searching and just can't find an answer anywhere.
They made this really easy. Alloc an NSTimer and initialize it with the fire date, using:
-(id)initWithFireDate:(NSDate *)date
interval:(NSTimeInterval)seconds
target:(id)target
selector:(SEL)aSelector
userInfo:(id)userInfo
repeats:(BOOL)repeats
then add it to the run loop using:
-(void)addTimer:(NSTimer *)aTimer forMode:(NSString *)mode
on the run loop, e.g. [NSRunLoop currentRunLoop]. Don't know if this will wake the device, or prevent it from sleeping.
edit some example code
// start in 5 minutes
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:300];
// fire every minute from then on
NSTimer *t = [[NSTimer alloc]
initWithFireDate:date
interval:60
target:self
selector:#selector(stuff:) // -(void)stuff:(NSTimer*)theTimer
userInfo:nil
repeats:YES
];
// make it work
[[NSRunLoop currentRunLoop] addTimer:t forMode:NSDefaultRunLoopMode];
and
-(void)stuff:(NSTimer*)theTimer
{
if ( done ) [theTimer invalidate];
}
If you need this to happen while your application is not running, have a look a UILocalNotification in iOS 4.0. It's unclear whether your application is running at the time that you need this notification or not, but in either case this class should get you pointed in the right direction.
http://developer.apple.com/iphone/library/documentation/iPhone/Reference/UILocalNotification_Class/Reference/Reference.html#//apple_ref/occ/cl/UILocalNotification

Using Reachability for Internet *or* local WiFi?

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.