While googling today, I couldn’t find a succinct explanation of this for a very common case: being notified of losing/gaining your network connection. So I’m going to summarize a simple approach here.
If you’re not familiar with all of the SCReachability jargon, there are three important terms:
- Reachability Target: The host you will test against to see if you can send data.
- Reachability Callback: The function which will be invoked when your Reachability Target’s reachability changes.
- Reachability Flags: A collection of bits that describe the reachability of a target.
Prior to 10.4, apparently the only way to check reachability was by polling a Reachability function. That’s no longer “how we do, yo.” Instead, the pattern is:
- Write a Reachability Callback.
- Create your Reachability Target.
- Register your Callback for your Target (SCNetworkReachabilitySetCallback).
- Schedule your Callback in your run loop (SCNetworkReachabilityScheduleWithRunLoop).
- Sit back and watch as your Reachability Callback is invoked when you unplug your network cable (or turn off your AirPort).
In your Callback, you’ll want to check the flags which are passed in. Be sure you understand how these flags work. It is not always intuitive (checking kSCNetworkFlagsReachable may not be sufficient for determing whether a host is reachable or not).
To get started, try running the SimpleReach sample app while plugging/un-plugging your network cable.
Finally, don’t forget to clean up your reachability target via SCNetworkReachabilityUnscheduleFromRunLoop and CFRelease.