Getting online/offline reachability notifications
Let me first stress the fact that I'm talking about the Mac OS X SDK, not iPhone.
In order to determine the "connectivity" and get the flags, I do something similar to:
#import <SystemConfiguration/SystemConfiguration.h>
const char *hostName = [@"google.com" cStringUsingEncoding:NSASCIIStringEncoding];
SCNetworkReachabilityRef target = SCNetworkReachabilityCreateWithName(NULL, hostName);
SCNetworkConnectionFlags flags = 0;
SCNetworkReachabil开发者_Python百科ityGetFlags(target, &flags);
Which is fine for just that -- getting info on the reachability of Google (which is exactly what I want to know).
Is there a way to add an observer to the changes? I've been looking into SCDynamicStore
, but I find the single example from Apple and the documentation a bit overwhelming.
Ideally I'd want to be able to set a function for flag changes, but this will suffice: notice when IP is "dropped"/released, and when it is obtained. (I could then do the reachability hardcoded in the function which is triggered on IP obtained).
Please don't hesitate to ask for elaborations.
Yes, you can use SCNetworkReachabilitySetCallback
and SCNetworkReachabilityScheduleWithRunLoop
. You don't need to use SCDynamicStore
unless you want to specifically watch a particular network interface.
If you want to take a look at a complete example, you can see what I did for NCIDpop (a network caller ID displayer). Search for SCNetworkReachability
in this file. The comments in the networkReachabilityCallback
function give you some idea of what state transitions to expect (which weren't terribly well documented when I wrote that code).
Use the Reachability classes from Apple Reachability sample code.
- It is a good sample to understand how Reachability works
- It will be much more easier to use (and will be Objective-C and not plain C)
Especially this sample make the SCReachability post a notification named kReachabilityChangedNotification
upon reachability changes, so you can add yourself as a listener to this notification easily using:
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
You can copy/paste the Reachability.h & .m files in your project (actually that's what everyone does; I don't know why Apple didn't add this Obj-C classes directly in their frameworks!)
Note: If you still want to use plain C, you can also call SCNetworkReachabilitySetCallback
yourself (as what is done in the above Apple sample) and give it a pointer to a C function in which you implement your code. If you do that, don't forget to schedule the reachability on the RunLoop to start the observation process, and remove it from the RunLoop when done
精彩评论