I am developing an iOS app that needs to check if Internet connection is available or not in it's several ViewController classes. To check network connectivity , I am using (Reachability library by Tony Million).
Here is what I am doing right now. In a ViewController class that requires connectivity checking , I am using this code blocks at ViewDidLoad....
Reachability* reach = [Reachability reachabilityWithHostname:@"www.google.com"];
reach.reachableBlock = ^(Reachability*reach)
{
NSLog(@"REACHABLE!"); // Load offline data from core data
};
reach.unreachableBlock = ^(Reachability*reach)
{
NSLog(@"UNREACHABLE!"); // Fetch data from Rest Api
};
[reach startNotifier];
But I am having some unexpected behaviour when network status changes and my app is in this ViewController, like sometimes fetching data from api runs like a loop again and again. I'm not sure if I have done something wrong in my codes, so expecting comments from experts.
Anyway, I am thinking an alternative solution to solve this issue and make codes cleaner and stable. I want to know from experts if it's good approach. I want to keep a BOOL Variable in AppDelegate called isNetworkConnected . Then in - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions , I want to run the above codes and set the variable isNetworkConnected YES/NO in that. So, the code will be like this...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
Reachability* reach = [Reachability reachabilityWithHostname:@"www.google.com"];
reach.reachableBlock = ^(Reachability*reach)
{
NSLog(@"REACHABLE!");
isNetworkConnected = YES ;
};
reach.unreachableBlock = ^(Reachability*reach)
{
NSLog(@"UNREACHABLE!");
isNetworkConnected = NO ;
};
[reach startNotifier];
// rest codes....
}
Then , in my ViewController , I'll do like this...
if(appdelegate.isNetworkConnected == YES){
// Fetch data from api
} else{
// Load offline data from Core data
}
That's it. I want to know whether my idea is good or bad , if I am doing any mistake or any better suggestion will be highly appreciated. Thanks in advance.