Search code examples
iosreachability

iOS app freeze during checking internet connection


In viewDidLoad of my initial view controller I check internet connection and if it available starts some downloading process.

If there is no any connection (WiFi or Mobile) or internet available - everything is ok. But, if device connected to WiFi without internet, application freeze.

if ([self isInternetAvail]) {
    [[Download sharedDownload] startUpdateProcessWithIndicatorInViewController:self];
}

This is the function:

- (BOOL)isInternetAvail
{
    NSString *hostName = @"google.com";
    Reachability *hostReach = [Reachability reachabilityWithHostName:hostName];
    NetworkStatus netStatus = [hostReach currentReachabilityStatus];
    if (netStatus == NotReachable) {
       return NO;
    } else {
       return YES;
    }
}

Application freezes on this line:

NetworkStatus netStatus = [hostReach currentReachabilityStatus];

More proper way to check internet connection is using NSNotificationCenter but in this case:

1) In didFinishLaunchingWithOptions:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(networkStateChanged:)
                                             name:kReachabilityChangedNotification
                                           object:nil];

hostReach = [Reachability reachabilityWithHostName:@"www.google.com"];
[hostReach startNotifier];
[self updateInternetAvailWithReachability: hostReach];

additional methods:

- (void)updateInternetAvailWithReachability: (Reachability *)curReach
{
    netStatus = [curReach currentReachabilityStatus];  
}

- (void)networkStateChanged:(NSNotification *)notification
{
    Reachability *curReach = [notification object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    [self updateInternetAvailWithReachability:curReach];
}

2) In viewDidLoad of my initial view controller:

AppDelegate *d = (AppDelegate *)[[UIApplication sharedApplication] delegate];
if (!d.netStatus == NotReachable) {
   [[Download sharedDownload] startUpdateProcessWithIndicatorInViewController:self];
}

On this step I get NotReachable and cannot start download

3) NSNotificationCenter tell me "Internet is available"

I need some advice how to prepare this.


Solution

  • When you are requesting to the server then reduce the timeoutInterval option and set it to minimum so that request should not wait for long to get the response by this way you can reduce the time of freezing the app. If you want to get rid of it completely then you should run all the process for network check in on another thread possibly in background thread.