Reputation: 518
I've seen plenty of examples here on how to check an internet connection is available but nobody seems to explain the best practice way of doing something once/ if it becomes available.
I'm using Tony Million's Reachability class and have a 'connection available' block that sets a boolean (Online) to true once the connection is available. The Reachability class is initialized in my app delegate didFinishLaunchingWithOptions but by the time my code checks the status of Online Reachability still hasn't finished figuring out if there's a connection, and so my app always sees itself as being offline when it first starts.
Now, I could put my connection-requiring code into the 'connection available' block but there's more than one place my app needs the internet so that's obviously not flexible enough for my needs.
The 'best' idea I had so far is to populate an array with methods that need the internet to do their thing and then have Reachability execute whatever is in that array once it knows there's a connection... but am I over-complicating matters here? Is there a better way of going about this?
Upvotes: 1
Views: 393
Reputation: 5405
This is roughly based on your "best idea". Tony Million's Reachability also posts notifications via NSNotificationCenter
when the internet connection changes. All your classes that need to do something when an internet connection becomes available, should register for this notification.
On the GitHub page there is an example for that: https://github.com/tonymillion/Reachability#another-simple-example
You would initialize the Reachability class in your app delegate, like you do right now. And then your other classes register for the kReachabilityChangedNotification
notification with the NSNotificationCenter
in their initializer. They also have to deregister from the NSNotificationCenter
in their dealloc method.
Here is some code you can use as starting point:
- (void)registerForReachabilityNotification
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object:nil];
}
- (void)deregisterFromNotifications
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)reachabilityChanged:(NSNotification *)notification
{
Reachability *reachability = notification.object;
switch ([reachability currentReachabilityStatus]) {
case NotReachable:
// No connection
break;
case ReachableViaWiFi:
case ReachableViaWWAN:
// Connection available
break;
}
}
Upvotes: 2